Angular gives us eight components hooks. Here are the life-cycle hooks available, in the order in which they are invoked:
1. ngOnChanges:
Called when any data-bound property of a directive changes. ngOnChanges only runs when the Input change comes from a template binding like
<component [someInput]="aValue">.
The hook receives a SimpleChanges object that contains the previous and current values for each properties.
2. ngOnInit:
Called once upon initialisation of the component.
3. ngDoCheck:
The DoCheck interface is used to detect changes manually which the angular change detection have overlooked. It gets called at every change detection cycle, so keeping what it does to a minimum is important for performance.
4. ngAfterContentInit:
This is called after components external content has been initialised.
5. ngAfterContentChecked:
Called after the projected content is checked.
6. ngAfterViewInit:
This is called after the component view and its child views has been initialised.
7. ngAfterViewChecked:
Called after a component’s view or child view is checked.
8. ngOnDestroy:
The ngOnDestroy or OnDestroy hook is called just before the Component/Directive instance is destroyed by Angular.
Example:
Let’s say we have a component used like this:
<my-app [title]="title" [content]="content"></my-app>
Component
import {
Component,
OnInit,
OnDestroy,
Input,
SimpleChanges,
OnChanges } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy, OnChanges {
@Input() title: string;
@Input() content: string;
constructor () { }
ngOnInit () {
console.log('Component Init');
}
ngOnDestroy () {
console.log('Component Destroy');
}
ngOnChanges(changes: SimpleChanges) {
console.log('Component Inputs Changes');
}
}
Using life-cycle hooks we can fine tune the behaviour of our components during creation, update and destruction.
If you like, or have any suggestion , please feel free to comment below.
0 Comments