Angular Lifecycle Execution flow from parent to child component

Sawatantra Chauhan
2 min readMay 29, 2021

--

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.

  1. ngOnChanges
  2. ngOnInit
  3. ngDoCheck
  4. ngAfterContentInit
  5. ngAfterContentChecked
  6. ngAfterViewInit
  7. ngAfterViewChecked
  8. 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.

  1. Parent: ngOnChanges
  2. Parent: ngOnInit
  3. Parent: ngDoCheck
  4. Parent: ngAfterContentInit
  5. Parent: ngAfterContentChecked
  6. Child: ngOnChanges
  7. Child: ngOnInit
  8. Child: ngDoCheck
  9. Child: ngAfterContentInit
  10. Child: ngAfterContentChecked
  11. Child: ngAfterViewInit
  12. Child: ngAfterViewChecked
  13. Parent: ngAfterViewInit
  14. 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.

Execution flow of Lifecycle hooks

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.

  1. Child: ngOnChanges
  2. Child: ngDoCheck
  3. Child: ngAfterContentChecked
  4. 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.

--

--