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

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


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


constructor

It's a class constructor that is triggered when Angular instantiates components. It's mostly used for DI and is called before Angular runs change detection. You can read more about it here:

ngOnInit(), ngAfterViewInit(), ngafterContentInit(), ngAfterViewChecked()

These are lifecycle hooks. They differ in the timing they are called and hence the data that is available in each of them. The timing with regards to other operations in change detection is clearly shown in the article:

Everything you need to know about change detection in Angular

The order is clearly defined:

  1. OnChanges lifecycle hook on a child component if bindings changed

Notifies whenever there's a change in the @Input bindings. Use it if you need constantly to track these bindings.

  1. OnInit and ngDoCheck on a child component (OnInit is called only during first check)

Notifies that @Input bindings are available. Use it if you don't need to constantly track these bindings.

  1. AfterContentInit and AfterContentChecked lifecycle hooks on child component instance (AfterContentInit is called only during first check)

Notifies that Angular ran change detection for the projected content (ng-content). Use it if you need to query projected elements using @ContentChildren decorator.

  1. AfterViewInit and AfterViewChecked lifecycle hooks on child component instance (AfterViewInit is called only during first check)

Notifies that Angular ran change detection for the view content. Use it if you need to query view elements using @ViewChildren decorator.

There's a lot of confusion about ngDoCheck lifecycle hook. To understand more read If you think ngDoCheck means your component is being checked — read this article.