3
votes

in a component life-cycle we have different interfaces that track different stages in the component
life-cycle, ex. OnInit, OnChanges, OnDestroy..etc
at the run-time how does angular trigger those methods?

for ex. ngOnChanges() is triggered when the @Input data is changed
now Angular have this logic i'm assuming
1- whenever angular detect changes in the @input data
2- angular check if this component class implements OnChanges
3- if true then trigger ngOnChanges()

and there is some logic for each of the life-cycle hooks
is this is the way that angular trigger life-cycle hooks?

2
Did you saw the docs? - Jota.Toledo

2 Answers

5
votes

Great question! Angular's life cycle hooks are implemented by the @angular/core library [source].

To prove this, run an angular cli project and in the (optionally chrome) dev tools, place a line break inside a life cycle hook like so:

Select line break inside life cycle hook

Refresh the page to catch the breakpoint and thus view the call stack:

Catch breakpoint

The Angular team obviously writes verbose code, so I don't think I need to explain the logic of the following statement that calls ngOnInit():

if ((view.state & ViewState.FirstCheck) && (def.flags & NodeFlags.OnInit)) {
    directive.ngOnInit();
}

The nice typescript version of this function can be found here.

1
votes

Angular.io documented with a image as below,

enter image description here

This illustrates the hierarchy of lifecycle hooks