Angular Lifecycle Hooks

Angular Lifecycle Hooks (Experiment Only)

Each component or directive has following life cycle and it is managed by Angular

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()

Component lifecycle hooks

Component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can handle it using interface implementation.


ngOnChanges()

on changes is a lifecycle hook that is called when any data-bound property of a directive changes. on changes is an interface that has a method declaration as below

ngOnChanges(changes: SimpleChanges) 


Have to import

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

When we used @Input() data-bound property in child component. If the @Input() references changed by the parent, then ngOnChanges() method is called.

Ex Source @StackBlitz


ngOnInit()

Called Once, After the 1st call of ngOnChanges()
Ex Source @StackBlitz



Output from Console:



ngDoCheck()

Called during every changes, after ngOnChanges() and ngOnInit().

Ex Source @StackBlitz


output from console: 

ngAfterContentInit()

Called once after the first ngDoCheck()



Ex Source @StackBlitz


output from console:

ngAfterContentChecked()

Called after the ngAfterContentInit() and every subsequent ngDoCheck()

Ex Source @StackBlitz

 output from console:


ngAfterViewInit()

Called once after the first ngAfterContentChecked().
Ex Source @StackBlitz

 output from console: 

ngAfterViewChecked()

Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
Ex Source @StackBlitz

output from console

ngOnDestroy()

Called just before Angular Dispose's the directive/component. try to navigate b/w component one & component 2.

 the output from console:


Your browser does not support iframes.

Post a Comment

0 Comments