If we have multiple instances of one component inside another component and we have constructor and ngOnInit() interface implemented in all of them, let's say we are just logging to the console, so will we have first constructor console.log() execution then console.log() of ngOnInit() for first instance of component and then second, third?
I'm getting all constructor console.log first then of ngOnInit()
CodePudding user response:
Yes this is right. The constructor will be called as the first. After the component/child components start to init. So if you log the complete lifecycle (see the docs)
After your application instantiates a component or directive by calling its constructor, Angular calls the hook methods you have implemented at the appropriate point in the lifecycle of that instance.
The output with 3 childs as example will be:
Constructor
Constructor
Constructor
OnInit
AfterViewInit
OnInit
AfterViewInit
OnInit
AfterViewInit
Why? The constructor is a simple, standard class
constructor every TypeScript class has. Angular init all components and then the first ngOnChanges
fire. And that only happens afterwards.
If Angular did this for every component created, it would start affecting performance, among other things.
If you try to call ref.detectChanges();
inside a childs constructor to force a update manually, a error occur:
ERROR Error: ASSERTION ERROR: Should be run in update mode [Expected=> false == true <=Actual].
This means Angular check changes after constructor was completed. And the first constructor is the parent. And this one is just finished when all child constructors finished, too.
In this example the child log first, at the end the parent.
Constructor Child
Constructor Child
Constructor Parent - ngOnChanges()
class parent {
constructor() {
let c1 = new child();
let c2 = new child();
console.log("Constructor Parent - ngOnChanges()");
}
}
...
class child {
constructor() {
console.log("Constructor Child");
}
}
I hope my words help to understanding this better.