Component Life Cycle Hooks in Angular

In this tutorial, we learn how to use Angular lifecycle hooks. The life cycle hooks are the methods that angular invokes on the directives and components as it creates, changes, and destroys them. Using lifecycle hooks we can fine-tune the behavior of our components during its creation, updating, and destruction.

What is Angular Component lifecycle hooks

When the angular application starts it creates and renders the root component. It then creates and renders its Childrens & their children. It forms a tree of components.

Once Angular loads the components, it starts the process of rendering the view.  To do that it needs to check the input properties, evaluate the data bindings & expressions, render the projected content etc. Angular also removes the component from the DOM, when it is no longer needs it.

Angular lets us know when these events happen using lifecycle hooks

The Angular life cycle hooks are nothing but callback function, which angular invokes when a certain event occurs during the component’s life cycle.

For example,

  • ngOnInit when Angular initializes the component for the first time.
  • When a component’s input property change, Angular invokes ngOnChanges
  • If the component is destroyed, Angular invokes ngOnDestroy

Angular lifecycle hooks

Here is the complete list of life cycle hooks, which angular invokes during the component life cycle. Angular invokes them when a certain event occurs.

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

Change detection Cycle

Before diving into the lifecycle hooks, we need to understand the change detection cycle.

Change detection is the mechanism by which angular keeps the template in sync with the component

Consider the following code.

Angular updates the DOM, whenever the value of the name changes. And it does it instantly.

How does angular know when the value of name changes?. It does so by running a change detection cycle on every event that may result in a change. It runs it on every input changes, DOM events, timer events like setTimeout() and setInterval() , http requests etc. 

During the change detection cycle angular checks each and every bound property in the template, with that of the component class. If it detects any changes it updates the DOM. 

Angular raises the life cycle hooks during the important stages of the change detection  mechanism.

Constructor

Life Cycle of a component begins, when Angular creates the component class. First method that gets invoked is class Constructor.

Constructor is neither a life cycle hook nor it is specific to Angular.  It is a Javascript feature. It is a method which is invoked, when a class is created. 

Angular makes use of a constructor to inject dependencies.

At this point, none of the components input properties are available to use. Neither its child components are constructed. Projected contents are also not available. 

Hence there is not much you can do in this method. And also it is recommend not to use it 

Once Angular instantiates the class, It kick-start the first change detection cycle of the component.

ngOnChanges

The Angular invokes ngOnChanges life cycle hook whenever any data-bound input property of the component or directive changes. Initializing the Input properties is the first task that angular carries during the change detection cycle. And if it detects any change in property, then it raises the ngOnChanges hook. It does so during every change detection cycle. This hook is not raised if change detection does not detect any changes.

Input properties are those properties, which we define using the @Input decorator. It is one of the ways by which a parent communicates with the child component.

In the following example, the child component declares the property message as the input property

The parent can send the data to the child using the property binding as shown below.

The change detector checks if such input properties of a component are changed by the parent component. If it is then it raises the ngOnChanges hook.

We used this life cycle hook in the tutorial Passing data to child component.

The change detector uses the === strict equality operator for detecting changes. Hence for objects, the hook is fired only if the references are changed. You can read more about it from Why ngOnChanges does not fire.

ngOnInit

The Angular raises the ngOnInit hook, after it creates the component and updates its input properties. It raises it after the ngOnChanges hook.

This hook is fired only once and immediately after its creation (during the first change detection).

This is a perfect place where you want to add any initialisation logic for your component.  Here you have access to every input property of the component. You can use them in  http get requests to get the data from the back end server or run some initialization logic etc.

But note that none of child components or projected content are available at this point. Hence any properties we decorate with @ViewChild, @ViewChildren , @ContentChild & @ContentChildren will not be available to use.

ngDoCheck

The Angular invokes the ngDoCheck hook event during every change detection cycle. This hook is invoked even if there is no change in any of the properties.

Angular invokes it after the ngOnChanges & ngOnInit hooks.

Use this hook to Implement a custom change detection, whenever Angular fails to detect the changes made to Input properties. This hook is particularly useful when you opt for the Onpush change detection strategy.

The Angular ngOnChanges hook does not detect all the changes made to the input properties.

ngAfterContentInit

ngAfterContentInit Life cycle hook is called after the Component’s projected content has been fully initialized. Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook. This hook is also raised, even if there is no content to project.

The content here refers to the external content injected from the parent component via Content Projection

The Angular Components can include the ng-content element, which acts as a placeholder for the content from the parent as shown below

Parent injects the content between the opening & closing element.  Angular passes this content to the child component

During the change detection cycle, Angular checks if the injected content has changed and updates the DOM.

This is a component only hook.

ngAfterContentChecked

ngAfterContentChecked Life cycle hook is called during every change detection cycle after Angular finishes checking of component’s projected content. Angular also updates the properties decorated with the ContentChild and ContentChildren before raising this hook. Angular calls this hook even if there is no projected content in the component

This hook is very similar to the ngAfterContentInit hook. Both are called after the external content is initialized, checked & updated. Only difference is that ngAfterContentChecked is raised after every change detection cycle. While ngAfterContentInit during the first change detection cycle.

This is a component only hook.

ngAfterViewInit

ngAfterViewInit hook is called after the Component’s View & all its child views are fully initialized. Angular also updates the properties decorated with the ViewChild & ViewChildren properties before raising this hook. 

The View here refers to the template of the current component and all its child components & directives. 

This hook is called during the first change detection cycle, where angular initializes the view for the first time

At this point all the lifecycle hook methods & change detection  of all child components & directives are processed & Component is completely ready  

This is a component only hook.

ngAfterViewChecked

The Angular fires this hook after it checks & updates the component’s views and child views. This event is fired after the ngAfterViewInit and after that during every change detection cycle

This hook is very similar to the ngAfterViewInit hook. Both are called after all the child components & directives are initialized and updated. Only difference is that ngAfterViewChecked is raised during every change detection cycle. While ngAfterViewInit during the first change detection cycle.

This is a component only hook.

ngOnDestroy

This hook is called just before the Component/Directive instance is destroyed by Angular

You can Perform any cleanup logic for the Component here. This is the correct place where you would like to Unsubscribe Observables and detach event handlers to avoid memory leaks.

How to Use Lifecycle Hooks

  1. Import Hook interfaces
  2. Declare that Component/directive Implements lifecycle hook interface
  3. Create the hook method

Let us build a simple component, which implements the ngOnInit hook

Create a Angular Project using Angular Cli. Open the app.component.ts

Import Hook interfaces

Import hook interfaces from the core module. The name of the Interface is hook name without ng. For example interface of ngOnInit hook is OnInit

Component Implements lifecycle hook interface

Next, define the AppComponent to implement OnInit interface

Create the hook method

The life cycle hook methods must use the same name as the hook.

The complete code for the app.component.ts.

Now, run the code and open the developer console. you will see the following

Note that the constructor event is fired before the OnInit hook.

The Order of Execution of Life Cycle Hooks

The Angular executes the hooks in the following order

On Component Creation

  1. OnChanges
  2. OnInit
  3. DoCheck
  4. AfterContentInit
  5. AfterContentChecked
  6. AfterViewInit
  7. AfterViewChecked

When the Component with Child Component is created

  1. OnChanges
  2. OnInit
  3. DoCheck
  4. AfterContentInit
  5. AfterContentChecked
    1. Child Component -> OnChanges
    2. Child Component -> OnInit
    3. Child Component -> DoCheck
    4. Child Component -> AfterContentInit
    5. Child Component -> AfterContentChecked
    6. Child Component -> AfterViewInit
    7. Child Component -> AfterViewChecked
  6. AfterViewInit
  7. AfterViewChecked

After The Component is Created

  1. OnChanges
  2. DoCheck
  3. AfterContentChecked
  4. AfterViewChecked

The OnChanges hook is fired only if there is an input property defined in the component and it changes. Otherwise, it will never fire

Angular Lifecycle hook Example

Source Code

app.component.ts

  • We are listening to all the hooks and logging them to the console.
  • There are two form fields message & content. We pass both to the child component. One as input property & the other via content projection
  • Using the hideChild form field we an add or remove the ChildComponent from the DOM. We are making use of the ngIf directive.
  • We pass the message property to ChildComponent using Property binding.
  • The content property is passed as projected content.

child.component.ts

  • We are listening to all the hooks
  • @Input decorator marks the message as input property. It will receive the data from the parent
  • <ng-content></ng-content> is the place holder to receive the projected content from the parent.
  • Two forms fields for customer object, which we pass it to the GrandChildComponent

grandchild.component.ts

  • We are listening to all the hooks
  • @Input decorator marks the customer as input property. It will receive the data from the parent

Run the code and check the console for the log messages

Conclusion

We learned about Component life cycle hooks in Angular.  The Angular generates following hooks OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked & OnDestroy. We then learned how to build an Application using OnInit life cycle hook. Finally, we looked at the Order of execution of these life cycle hooks

6 thoughts on “Component Life Cycle Hooks in Angular”

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top