Implements Angular’s core functionality, low-level services, and utilities.
Some of the core classes/interfaces/functions are as follows :
1. EventEmitter
It is a Class, In Angular, a component can emit an event using @Output and EventEmitter. Both are parts of the @angular/core.
It emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance.
appchild.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button class='btn btn-primary' (click)="valueChanged()">Click me</button> `
})
export class AppChildComponent {
@Output() valueChange = new EventEmitter();
Counter = 0;
valueChanged() { // You can give any function name
this.counter = this.counter + 1;
this.valueChange.emit(this.counter);
}
}
to emit values in the parent component.
2. OnDestroy
It is an interface, it is a lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed.
// its own Definition
interface OnDestroy {
ngOnDestroy(): void
}
// Usage of ngOnDestroy()
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
ngOnDestroy() {
// ...
}
}
3. OnInit
It is an interface, it is a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. Define an ngOnInit() method to handle any additional initialization tasks.
It is invoked only once when the directive is instantiated.
// its own Definition
interface OnInit {
ngOnInit(): void
}
// Usage of ngOnInit()
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
ngOnInit() {
// ...
}
}
4. ViewChild
It is one of the decorators, it is a Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.
// EXAMPLE
import {Component, Directive, Input, ViewChild} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id !: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
<button (click)="toggle()">Toggle</button>
<div>Selected: {{selectedPane}}</div>
`,
})
export class ViewChildComp {
@ViewChild(Pane, {static: false})
set pane(v: Pane) {
setTimeout(() => { this.selectedPane = v.id; }, 0);
}
selectedPane: string = '';
shouldShow = true;
toggle() { this.shouldShow = !this.shouldShow; }
}
Summary
In this tutorial we learnt about the angular core APIs , few classes, interfaces and functions.
Hope you like it !