Angular 5 Lifecycle Hooks for 2Mins Read

Angular 5 Lifecycle Hooks for 2Mins Read

Angular 5 Lifecycle Hooks for 2Mins Read:

What are lifecycle hooks ?
Lifecycle hooks are the different phases during component initializing and projection to view, when a new component is encountered in the selector, then angular takes care of initializing the component to project it in the view with different phases. These are called lifecycle hooks in angular.

All these lifecycle hooks are called after the component’s constructor called.

 

These are lifecycle hooks of angular:

ngOnChanges():

  • Executed multiple times.
  • Called whenever a new input bounded property changes (eg: @Input decorated property changes)

ngOnInit():

  • Initialized only during the component initialization.
  • Runs only once.

ngDoCheck():

  • Runs Multiple times.
  • Called during any template/property/event changes even it does not change or make sense.
  • Can be used to do something at all the changes / change detection.

ngAfterContentInit():

Called after the content has been initialized and projected to view, but still it is in typescript component level only and not displayed in the view still.

 

ngAfterContentChecked():

Called every time the content has been projected + doCheck completed.

In realtime, I was facing the issue like when the routing url changed, the content alone was not getting refreshed when I do from the same page.

So I copied all those url value reading from ngOnInit() to ngAfterContentChecked() to refresh the view as well.

 

ngAfterViewInit():

  • Once our template view has been initialized or projected.
  • Template views includes it’s child views too.

 

ngAfterViewChecked():

Called everytime the view has been projected + doCheck completed

 

ngOnDestroy():

  • Called once the component is about to be destroyed.
  • Runs only once.

 

 

Things to Remember / Note:

  • All the above (onChanges, onInit, DoCheck etc..) should be imported from @angulare/core
  • ngOnInit() and ngOnDestroy() – called only once.
  • ngAfterContentInit() and ngAfterViewInit() – Called after the projected content and view has been initialized.
  • ngAfterContentChecked() and ngAfterViewChecked() – Called every time the projected content and view have been checked.
  • ngOnChanges() – Called after @Input property changes. (Bounded input properties)
  • ngDoCheck() – Called during all the change detection run.

 

Angular lifecycle hooks are little tricky to understand if you are completely new to angular. But you should know it in highlevel atleast to be a better angular programmer.

If someone will be able to explain much better than this article, please add your content/examples in the below comments area to update and help angular new developers.

 

478 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *