Angular: Constructor vs ngOnInit, Basic differences
Constructor is the feature provided by ES6 (i.e. Typescript)
ngOnInit is provided by Angular itself
interface OnInit {
}
Before seeing what was the order of execution let’s see if both is not available what will happen,
You can see that the Angular s happily compiling and executing the code even the constructor or ngInit is not present
As a next step we are trying to implement the ngOnInit interface explicitly, let’s see what will happen
We are getting the following error
Class 'AppComponent' incorrectly implements interface
'OnInit'.
Property 'ngOnInit' is missing in type 'AppComponent' but required in type
'OnInit'.
So we need to implement the ngOnInit if we are specifying in the class
After implementing the ngOnInit we are getting the page back to normal
So what is the order of execution now.
To find this we will create a constructor and provide the
console.log
In the output we will see the constructor is loading first and then the ngOnInit
Example available at
https://stackblitz.com/edit/angular-ivy-avjhdh
Comments