Angular Lifecycle Execution flow from parent to child component
This article consists of explanation about the sequence in which lifecycle hooks execute when we have parent child relation between components.
We will also discuss which lifecycle hook we can use in different scenarios.
There are basically eight lifecycle hooks in angular for a component which will get invoked based on the state in which the component is in.
Below are the hooks.
- ngOnChanges
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
- ngOnDestroy
Now let’s take an Example for two components, Component Parent and Component Child. Consider we have added all lifecycle hook in parent as well as child Component, and also we have one inbound property “message” which we are passing from Parent to child.
E.g. Parent template: <Child [message]=”message”></Child>
Initialization
At the time of initialization the sequence in which lifecycle hook will execute is.
- Parent: ngOnChanges
- Parent: ngOnInit
- Parent: ngDoCheck
- Parent: ngAfterContentInit
- Parent: ngAfterContentChecked
- Child: ngOnChanges
- Child: ngOnInit
- Child: ngDoCheck
- Child: ngAfterContentInit
- Child: ngAfterContentChecked
- Child: ngAfterViewInit
- Child: ngAfterViewChecked
- Parent: ngAfterViewInit
- Parent: ngAfterViewChecked
After ngAfterContentChecked of Parent all lifecycle hook of Child will get executed(Except ngOnDestroy) and after that ngAfterViewInit and ngAfterViewChecked of parent will get executed.
By looking at above flow, it’s very important which operation to put in which lifecycle hook. e.g. If you want to do any operation after all the child is been initialized, Use ngAfterViewInit since it is invoked after all child is done with initialization.
Change of Inbound properties
Angular change detection for child component gets triggered whenever we change inbound properties of parent.
Whenever change detection happens, It executes four life cycle hooks which are ngOnChanges, ngDoCheck, ngAfterContentChecked and ngAfterViewChecked.
In over above example if we change “message” variable in Parent component, change detection will trigger in Child component. And it will invoke below hooks.
- Child: ngOnChanges
- Child: ngDoCheck
- Child: ngAfterContentChecked
- Child: ngAfterViewChecked
Again it’s very important to choose a hook for putting operation if we want to trigger a particular operation whenever there is a change event. Most of the time we go with ngOnChanges.
But if we want all child components changes to be done first then we can go for ngAfterViewChecked.