Techcookies

Angular life cycle hooks

Angular, JavaScript | Sun Nov 17 2019 | 2 min read

Overview

Angular manages creation, initialization, rendering, data-binding and removal of component and its child components. Angular offers life cycle hooks that provide more control over these key life moments and the ability to act when they occur. Angular executes the constructor first then only execution of all other life cycle hook methods occurs explicitly in following order:

Hooks for component

ngOnChanges

ngOnChanges called after set/changes in Input properties with SimpleChanges object as parameter having current and previous property values. Angular only calls ngOnChanges when the value of the property changes, it doesn't report changes in inner properties as change in property doesn't change in object reference in JavaScript.

ngOnInit

This life cycle hook runs only once when component is initialized. This is the perfect place for fetching data and component initializations.

ngDoCheck

This life cycle hook called during every change detection run, frequency of calling this hooks is very high. We can implement our own change detection algorithm for the given component.

ngOnDestroy

This will be called just before Angular destroys the component.

Hooks for child component

ngAfterContentInit

This life cycle hook called after external content projection into view(using ng-content).

ngAfterContentChecked

ngAfterContentChecked hook is called after Angular checks the content projected into the component. It runs initially after the ngAfterContentInit finishes and every time the change detection runs.

ngAfterViewInit

ngAfterContentInit called after component and all child components view has been initialized. It runs only during first change detection cycle.

ngAfterViewChecked

ngAfterViewChecked called after every time the view of the given component has been checked by the change detection mechanism.

How to use life cycle hooks

The steps to use life cycle hooks are as follows:

  • First, import the hook interface.
  • Declare hook interface in component or directive to implement
  • Next, you ought to generate the hook method.
javascript
import { Component, OnInit, OnChanges, SimpleChanges, Input,
  DoCheck,
  AfterContentInit,
  AfterContentChecked,
  AfterViewInit,
  AfterViewChecked,
  OnDestroy } from '@angular/core';
  • Parent component - ngOnInit
  • Child component - ngOnInit
  • Child component - ngAfterContentInit
  • Child component - ngAfterContentChecked
  • Child component - ngAfterViewInit
  • Child component - ngAfterViewChecked
  • Child component - ngAfterContentChecked
  • Child component - ngAfterViewChecked