What is the difference between ngOnInit(), ngAfterViewInit(), ngafterContentInit(), ngAfterViewChecked() and a constructor()? How do we implement them in the Angular 2? What are their purposes and usages? Where all will it be useful for implementing them?
Thanks.
The constructor() should only be used to initialize class members but shouldn't do actual "work". So we should use constructor() to setup Dependency Injection, Initialization of class fields etc. ngOnInit() is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.
ngOnInit() is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated. ngAfterViewInit() is called after a component's view, and its children's views, are created.
ngAfterContentInit : This is called after components external content has been initialized. ngAfterViewInit : This is called after the component view and its child views has been initialized.
ngAfterViewChecked()Called after the ngAfterViewInit and every subsequent ngAfterContentChecked(). That means Checked states to say it runs after Init . Initialization means it runs at first and Checking for the changes runs many times after initialization.
Those are life cycle hooks that you can tap into to perform operations and different times of a components life cycle.
There is an excellent guide on the topic in the official angular documentation: https://angular.io/guide/lifecycle-hooks
A component has a lifecycle managed by Angular.
Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.
Angular offers lifecycle hooks that provide visibility into these key life moments and the ability to act when they occur.
The following diagram from the official documentation describes the order of lifecycle hooks:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With