Contact Us

Angular lifecycle hooks : Full guide

 - 
July 25, 2022
Angular life cycle hooks : full guide

Angular provides a list of methods that we call lifecycle hooks. These lifecycle hooks are very important to manage components and directives after creating them in Angular. Each function of the list will execute at a specific time in the life of the component from the second we get into it to the last second we leave it.

Using the lifecycle hooks gives us a big control of our application, especially if we want to execute a set of code when the component first loads or when we leave the component. These use cases are very common on an Angular application that’s why we need these lifecycle hooks.

Lifecycle hooks for components and directives

Angular is one of the web app development frameworks that uses the concept of component which makes it easy to manage and maintain the code. The component in angular is a class that has the decorator @Component . Here is how the component looks like

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

}

Another concept that Angular uses which is similar to the component is the directive. Directive is a class that has the decorator @Directive and its job is to make changes and add functionalities to the DOM. The difference between the component and directive is that the component functions on the UI side. However, the directive will work on non UI parts of the app, it will make changes on the DOM. Here is how the directive looks like.

import { Directive } from '@angular/core';
@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
}

Here is the list of the lifecycle hooks in Angular 

Angular lifecycle hooks

1) Constructor

Normally the constructor is not a function provided by Angular specifically. It is a function that exists in any JS class, and since the components and the directives are classed then they have the constructor method. 

This method triggers whenever Angular creates an instance of the component or the directive class using the new keyword.

1) OnChanges

OnChanges is a lifecycle hook that is called once the component is created, and everytime there is a change in any of the values coming from the parent component (@Input variables) or directive data changes. Once Angular detect a change in any input property it will raise the ngOnChanges method which gives access to the current value and the previous value of the property. 
 We can define input properties or variables using the @Input decorator, and the objective of this kind of variables is to pass data from the parent to the child component, and we can define an Input variable like this

@Input() test: string;

We can pass data from the parent to the child component like this

<app-root [message]="test"></app-root>

As we described earlier the ngOnChanges method gives us access to the current and the previous value of the input variable using the SampleChanges class. Here is how we can get the values from the function.

import { Component, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  ngOnChanges(changes: SimpleChanges): void {
    console.log(changes);
  }
}

3) OnInit

The OnInit hook is being called by Angular after the creation of the component / the directive. It is mostly used to initialize variables or get data from services. We can implement this hook using the ngOnInit function. It will be executed only once and immediately after the creation of the component.

This method is the perfect to initialize all the variables in the component, because it gives access to all and every element of the component. That’s why it is the best place to send http requests to get or post data in the backend.

The following is an example of implementing the ngOnInit method.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  ngOnInit(): void {
    console.log('ngOnInit');
    
  }
}

4) ngDoCheck

This ngDoCheck hook is used to detect changes that can not be detected by the ngOnChanges hook. It is very useful for custom change detection. This hook will be invoked right after ngOnInit and ngOnChanges hooks. 

If you are planning to go advanced with Angular then using the ngDoCheck hook is very useful because it will help you as a developer to create your custom change detection in the component or the directive.

Here is an example that will show you exactly how to use ngDoCheck hook in your project.

import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements DoCheck {

  ngDoCheck(): void {
    console.log('ngDoCheck');
  }

}

ngDoCheck is very useful in some use cases like when there is a change in the parent component but there is no change in the @Input variable and you want to capture the change, in this case the ngDoCheck will be the best solution for that.

5) ngAfterContentInit

This hook will be invoked by Angular only once. It will be executed when the content like the html code of the component is initialized which means there is something projected to the component’s view. 

The next snippet of code will show you exactly how to implement this hook in your component.

import { AfterContentInit, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterContentInit {
  
  ngAfterContentInit(): void {
    console.log('AfterContentInit');
  }

}

6) ngAfterContentChecked

Right after Angular finishes checking the projection of the content in the component, the ngAfterContentChecked hook will be invoked in every change detection. Before invoking this hook Angular will update the variables created with the decorator @ContentChild and the decorator @ContentChildren

The hook will be called even if there is no content projected in the component.

Here is a brief example of how to use the ngAfterContentChecked.

import { AfterContentChecked, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterContentChecked {

  ngAfterContentChecked() {
    console.log('AfterContentChecked');
  }

}

7) ngAfterViewInit

The ngAfterViewInit hook will be invoked right after the component’s view and all its children are done loading. The variables created using the @ViewChild and @ViewChildren decorators will be updated by the Angular system before invoking the ngAfterViewInit hook.

The best use case to use this hook is when you want to make some changes on HTML elements right after the creation of the component.

Here is an example of implementing this hook.

import { AfterViewInit, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
 
  ngAfterViewInit() {
    console.log('AfterViewInit');
  }

}

8) ngOnDestroy

This hook will be executed when Angular destroy the component or the directive, so for example if we are on a page that uses a component and we quit that page, that means that component will be destroyed.

Developers uses ngOnDestroy mostly to unsubscribe to any subscription in the component which will help the application’s performance.

import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnDestroy {
  constructor() {
    console.log('AppComponent constructor');
  }
  ngOnDestroy() {
    console.log('AppComponent ngOnDestroy');
  }

}

Conclusion

In this article we understood the Angular lifecycle hooks, how they work and their objectives. We explained every single one of them in details and how to use with a real world example. 

As an Angular developer you need to know exactly the purpose of lifecycle hooks and how they work because you will use them in any project you work on.

I hope you enjoyed this post and Thank you so much for reading.

Web Design Services

Looking for a web design agency to bring your business online and build the website you need to get more high quality clients ?
GrowYourBusiness.tech agency is ready to help you build your beautiful looking website.

Latest Blogs

We are a team of creative thinkers and problem solvers dedicated to expanding the limits of what is possible by helping brands achieve their goals.

Social Media

Copyright © 2021 Grow Your Business. All rights reserved.
crossmenu