Angular Lifecycle Hooks

When Angular finds a selector, it instantiates a new component and adds it into the DOM. in this creation process, Angular goes through a couple of different phases and we can hook into these phases by implementing some methods that Angular will call if they are present.

Here is a list of  lifecycle hooks in the order they execute:

  • ngOnChanges: Called after a bound input property changes
  • ngOnInit: Called once the component is initialized
  • ngDoCheck: Called during every change detection run
  • ngAfterContentInit: Called after content (ng-content) has been projected into view
  • ngAfterContentChecked: called every time the projected content has been checked
  • ngAfterViewInit: Called after the component’s view (and child views) has been initialized
  • ngAfterViewChecked: Called every time the view (and child views) have been checked
  • ngOnDestroy: Called once the component is about to be destroyed

ngOnchages will be execute when the component is created and whenever one of our bound input properties(properties with @Input decorator) changes.

ngOnInit will run after the constructor and the component is initialized, means that it has not been added to the DOM yet, but Angular finished the basic initialization and the properties can now be accessed and initialized.

ngDnCheck will called a lot since change detection is the system by which Angular determines whether something changed on the template or on the component itself.