首页 > 解决方案 > ngOnInit vs constructor in Angular

问题描述

From here: https://www.angularjswiki.com/angular/what-is-the-difference-between-constructor-and-ngoninit-in-angular/#ngoninit-vs-constructor-in-angular

ngOnInit: Invoked by Angular when component is initialized
constructor: Constructor is automatically called at the time of creating object of the class

How do we know when component is initialized? Which function is responsible for this?

ngOnInit: Everything is ready at the time of invocation.
constructor: Not everything in component is initialized at the time of invocation

What is "everything" that is ready at the time of invocation?

https://angular.io/api/core/OnInit

A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

Also, please explain the bold lines in the above quote.

标签: angular

解决方案


Here is the exection order of various functions during the lifecycle of a component

  • constructor
  • OnChanges
  • OnInit
  • DoCheck
  • AfterContentInit
  • AfterContentChecked
  • AfterViewInit
  • AfterViewChecked
  • OnDestroy

So by the time the constructor is called the change detection has not yet completed and some of the variables might not be initialized (for eg. input variables with @Input() decorator). However by the time ngOnInit() is hit, the component has been properly initialized.


推荐阅读