How does angular actually trigger lifecycle hooks?

in the life cycle , we have different interfaces that track different stages of the component. life cycle, for example. OnInit, OnChanges, OnDestroy..etc
at runtime angular runs these methods?

for ex. ngOnChanges () is triggered when data changes @Input
angular now has this logic I assume
1- whenever angular detects changes in data @input
2- angular check if this component class implements OnChanges 3, if true then trigger ngOnChanges ()

and there is some logic for each of the lifecycle hooks
- is this the way angular does the lifecycle hooks?

+3


source to share


2 answers


Great question! Angular lifecycle hooks are implemented by the library [ source ]. @angular/core

To prove it, run the project angular cli

and in tools (optional chrome) dev, place a line break inside life like so:

Select line break inside lifecycle loop

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



Frontal breakpoint

The Angular team is explicitly writing verbal code, so I don't think I need to explain the logic behind the following statement that calls ngOnInit()

:

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

      

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

+3


source


Angular.io is documented by image as below,

enter image description here



This illustrates the lifecycle bindings hierarchy

0


source







All Articles