Raed Khalaf
Raed Khalaf

Reputation: 2065

How does angular actually trigger the life-cycle hooks?

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?

Upvotes: 3

Views: 2537

Answers (3)

Paritosh
Paritosh

Reputation: 61

Diagram contains list of all the 8 life-cycle hooks(methods) and the sequence in which they are executed.

Application starts with instantiation of a component or directive by calling its constructor which is followed by the life-cycle hooks.

  • Black arrows represent the path followed once on instantiation.
  • After the component or directive is loaded if there is any change in input data, path followed is represented by red arrows. enter image description here

Upvotes: 0

Tom
Tom

Reputation: 5121

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.

Upvotes: 6

Aravind
Aravind

Reputation: 41533

Angular.io documented with a image as below,

enter image description here

This illustrates the hierarchy of lifecycle hooks

Upvotes: 1

Related Questions