Angular Lifecycle Hook

A Component has life-cycle which managed by Angular. Angular directive & component have same life cycle as creates,updated & destroy them. When create component following sequence hooks called.

  1. Constructor
  2. ngOnChanges
  3. ngOnInit
  4. ngDoCheck
    • ngAfterContentInit
    • ngAfterContentChecked
    • ngAfterViewInit
    • ngAfterViewChecked
  5. ngOnDestroy



Hooks for the component

Constructor
This hook invoked when we create component or directive by initialize Class.

ngOnChanges
This hook invoked when ever any of the input properties changed for the component.

ngOnInit
This hook invoked when component initialized. This hook only called once after the first ngOnChanges()

ngDoCheck
This hook invoked when the change detector of the given component. It allows to implements our own change detection.

Most Important
ngDoCheck & ngOnChanges should not implement for same component.

ngAfterContentInit
This hook invoked after Angular projects external content into the component’s view, it Called once after the first ngDoCheck().

ngAfterContentChecked
This hook invoked each time the content of the given component has been checked by the change detection mechanism of Angular.

ngAfterViewInit
This hook invoked when the component’s view has been initialized.


ngAfterViewChecked
This hook invoked each time the view of the given component has been checked by change detection mechanism of Angular.

ngOnDestroy
This hook invoked just before Angular destroy the component.

Example for how to use Hook in component.


import {OnChanges, OnInit, OnDestroy} from '@angular/core';
class helpComponent implements on OnInit,OnDestroy,OnChanges {

constructor(){
// It calls when component initialize.
}

ngOnInit(){
console.log("ngOnInit");
}

ngOnChanges(){
console.log("ngOnChanges");
}

ngOnDestroy(){
console.log("ngOnDestroy");
}

}
Spread the love
  • 22
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •