Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 361
Ashfaque Rifaye Avatar asked Sep 20 '17 06:09

Ashfaque Rifaye


People also ask

What is the difference between ngOnInit () and constructor () of a component?

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.

What is the difference between ngOnInit and ngAfterViewInit?

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.

What is difference between ngAfterContentInit and ngAfterViewInit?

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.

What is the difference between ngAfterViewInit and ngAfterViewChecked?

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.


1 Answers

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

like image 146
Fredrik Lundin Avatar answered Oct 14 '22 16:10

Fredrik Lundin