Reputation: 884
I'm new to Angular and I tried some code where the property set is being triggered before the ngOnInit().
export class App implements OnInit{
isTriggered = false;
constructor(){
...
}
ngOnInit(){
this.isTriggered = true;
}
}
I'm not sure how this works but isTriggered = false;
is getting triggered first before the debugger moves to this.isTriggered = true;
Can someone explain me why this is happening and whats the approach to trigger this.isTriggered = true;
from ngOnInit()
Upvotes: 0
Views: 1136
Reputation: 641
The issue is that ngOnInit
is an Angular lifecycle method, whereas the isTriggered = false
is a class property, native to Javascript, same as if you had placed it inside the constructor.
In the old way of doing things before Javascript Classes even came around, it might've been more obvious.
export function App() {
this.isTriggered = false;
this.ngOnInit = function() { };
}
Seen this way, it's pretty obvious that isTriggered = false
will be invoked immediately upon creating a new App()
vs. ngOnInit
which will only be invoked by something calling ngOnInit
after the new
object is already created.
Angular lifecycle methods will happen on Angular's framework timing, meaning it's going to happen sometime after that class is initialized. During the initialization of that class, the class property will be set, hence why you see the debugger go to that line first.
Upvotes: 1
Reputation: 2017
It's pretty obvious actually. To invoke ngOnInit you need an instance of App class. When you create an instance all declared fields are initialized first.
Upvotes: 1
Reputation: 67
When you declare isTriggered = false
, that is the same as doing it as initializing it as if it was a part of the constructor. ngOnInit happens afterwards, so that's why you're getting it set to false and then to true.
You can declare isTriggered
without assigning it a value simply by removing = false;
and then only in ngOnInit assign it to true if that's what you're looking to do.
Upvotes: 0