What is the difference between ngOnInit(), ngAfterViewInit(), ngafterContentInit(), ngAfterViewChecked() and a constructor()?

Ashfaque Rifaye picture Ashfaque Rifaye · Sep 20, 2017 · Viewed 11.3k times · Source

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.

Answer

Fredrik Lundin picture Fredrik Lundin · Sep 20, 2017

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:

enter image description here