What the 'Angular Lifecycle Hooks' 🤔

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Why do we need lifecycle hooks?

Modern front-end frameworks move the application from state to state. Data fuels these updates. These technologies interact with the data which in turn transitions the state. With every state change, there are many specific moments where certain assets become available.

At one instance the template might be ready, in another data will have finished uploading. Coding for each instance requires a means of detection. Lifecycle hooks answer this need. Modern front-end frameworks package themselves with a variety of lifecycle hooks. Angular is no exception.

Learning Objectives

  • Understand the different phases an Angular component goes through from being created to being destroyed.

  • Know how to hook into those phases and run your own code.

  • Know the order in which the different phases happen and what triggers each phase.

Phases

A component in Angular has a life-cycle, a number of different phases it goes through from birth to death.

We can hook into those different phases to get some pretty fine grained control of our application.

To do this we add some specific methods to our component class which get called during each of these life-cycle phases, we call those methods hooks.

The hooks are executed in this order:

image.png (Source: codecraft.tv)

You don't have to implement all (or any) of the lifecycle hooks, just the ones you need.

These phases are broadly split up into phases that are linked to the component itself and phases that are linked to the children of that component.

Hooks for the Component

constructor

This is invoked when Angular creates a component or directive by calling new on the class.

ngOnChanges

Invoked every time there is a change in one of th input properties of the component.

ngOnInit

Invoked when given component has been initialized. This hook is only called once after the first ngOnChanges

ngDoCheck

Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component.

Important

ngDoCheck and ngOnChanges should not be implemented together on the same component.

ngOnDestroy

This method will be invoked just before Angular destroys the component. Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.

Hooks for the Component’s Children

These hooks are only called for components and not directives.

ngAfterContentInit

Invoked after Angular performs any content projection into the component’s view (see the previous lecture on Content Projection for more info).

ngAfterContentChecked

Invoked each time the content of the given component has been checked by the change detection mechanism of Angular.

ngAfterViewInit

Invoked when the component’s view has been fully initialized.

ngAfterViewChecked

Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.

How to use Hooks

I am not going to explaining you using code examples. But you can find the examples here.

This is how the code will look if we use the hooks:

class JokeComponent {
  @Input('joke') data: Joke;

  constructor() {
    console.log(`new - data is ${this.data}`);
  }

  ngOnChanges() {
    console.log(`ngOnChanges - data is ${this.data}`);
  }

  ngOnInit() {
    console.log(`ngOnInit  - data is ${this.data}`);
  }

  ngDoCheck() {
    console.log("ngDoCheck")
  }

  ngAfterContentInit() {
    console.log("ngAfterContentInit");
  }

  ngAfterContentChecked() {
    console.log("ngAfterContentChecked");
  }

  ngAfterViewInit() {
    console.log("ngAfterViewInit");
  }

  ngAfterViewChecked() {
    console.log("ngAfterViewChecked");
  }

  ngOnDestroy() {
    console.log("ngOnDestroy");
  }
}

Summary

Using life-cycle hooks we can fine tune the behavior of our components during creation, update and destruction.

We use the ngOnInit hook most often, this is where we place any initialization logic for our component. It’s preferred over initializing via the constructor since in the constructor we don’t yet have access to the input properties whereas by the time ngOnInit is called they have been bound to and are available to use.

ngOnChanges is the second most common hook, this is where we can find out details about which input properties have changed and how they have changed.

The third most common hook is ngOnDestroy which is where we place any cleanup logic for our component.

No Comments Yet