Angular JS

Component Life Cycle Hooks in Angular

황기하 2022. 1. 15.

https://www.tektutorialshub.com/angular/angular-component-life-cycle-hooks/

 

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.

1
2
3
4
 
<div>Hello {{name}}</div>
 
 

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

1
2
3
 
@Input() message:string
 

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

1
2
3
4
5
 
<app-child [message]="message">
</app-child>
 
 

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

1
2
3
4
5
 
<h2>Child Component</h2>
<ng-content></ng-content>   <!-- placehodler for content from parent -->
 
 

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

1
2
3
4
5
 
<h1>Parent Component</h1>
<app-child> This <b>content</b> is injected from parent</app-child>
 
 

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

1
2
3
 
import { Component,OnInit } from '@angular/core'
 

Component Implements lifecycle hook interface

Next, define the AppComponent to implement OnInit interface

1
2
3
 
export class AppComponent implements OnInit {
 

Create the hook method

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

1
2
3
4
5
 
ngOnInit() {
    console.log("AppComponent:OnInit");
  }
 

The complete code for the app.component.ts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
import { Component,OnInit } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
      <h2>Life Cycle Hook</h2>` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  constructor() {
    console.log("AppComponent:Constructor");
  }
 
  ngOnInit() {
    console.log("AppComponent:OnInit");
  }
 
}
 

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

1
2
3
4
 
AppComponent:Constructor
AppComponent:OnInit
 

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
 
import { ChangeDetectionStrategy, Component, VERSION } from "@angular/core";
 
@Component({
  selector: "my-app",
  changeDetection:ChangeDetectionStrategy.Default,
  template: `
    <h1>Angular Life Cycle Hooks</h1>
    Reference :
    <a
      >Angular Life Cycle Hooks</a
    >
 
    <h1>Root Component</h1>
 
 
    <br />
    <input
      type="text"
      name="message"
      [(ngModel)]="message"
      autocomplete="off"
    />
    <br />
    <input
      type="text"
      name="content"
      [(ngModel)]="content"
      autocomplete="off"
    />
 
 
    <br />
    hide child :
    <input
      type="checkbox"
      name="hideChild"
      [(ngModel)]="hideChild"
      autocomplete="off"
    />
 
    <br />
    <br />
    <app-child [message]="message" *ngIf="!hideChild">
      <!-- Injected Content -->
      <b> {{ content }} </b>
    </app-child>
 
    
  `
})
export class AppComponent {
  name = "Angular " + VERSION.major;
 
  message = "Hello";
  content = "Hello";
  hideChild=false;
 
  constructor() {
    console.log("AppComponent:Contructed");
  }
 
  ngOnChanges() {
    console.log("AppComponent:ngOnChanges");
  }
 
  ngOnInit() {
    console.log("AppComponent:ngOnInit");
  }
 
  ngDoCheck() {
    console.log("AppComponent:DoCheck");
  }
 
  ngAfterContentInit() {
    console.log("AppComponent:ngAfterContentInit");
  }
 
  ngAfterContentChecked() {
    console.log("AppComponent:AfterContentChecked");
  }
 
  ngAfterViewInit() {
    console.log("AppComponent:AfterViewInit");
  }
 
  ngAfterViewChecked() {
    console.log("AppComponent:AfterViewChecked");
  }
 
  ngOnDestroy() {
    console.log("AppComponent:ngOnDestroy");
  }
 
}
 
 
 
 
 
  • 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
 
import { ChangeDetectionStrategy, Component, Input,  OnInit } from '@angular/core';
import { Customer } from './customer';
 
@Component({
  selector: 'app-child',
  changeDetection:ChangeDetectionStrategy.Default,
  template: `
  
      <h2>child component</h2>
 
      <br>
      <!-- Data as a input -->
      Message from Parent via @input {{message}}
      <br><br>
      <!-- Injected Content -->
      Message from Parent via content injection
      <ng-content></ng-content>
 
      <br><br><br>
      Code :
      <input type="text" name="code" [(ngModel)]="customer.code" autocomplete="off">
      <br><br>
      Name:
      <input type="text" name="name" [(ngModel)]="customer.name" autocomplete="off">
 
      <app-grand-child [customer]="customer"></app-grand-child>
  
  `
  
})
export class ChildComponent {
 
  @Input() message:string
 
  customer:Customer = new Customer()
 
 
constructor() {
    console.log("  ChildComponent:Contructed");
  }
 
  ngOnChanges() {
    console.log("  ChildComponent:ngOnChanges");
  }
 
  ngOnInit() {
    console.log("  ChildComponent:ngOnInit");
  }
 
  ngDoCheck() {
    console.log("  ChildComponent:DoCheck");
  }
 
  ngAfterContentInit() {
    console.log("  ChildComponent:ngAfterContentInit");
  }
 
  ngAfterContentChecked() {
    console.log("  ChildComponent:AfterContentChecked");
  }
 
  ngAfterViewInit() {
    console.log("  ChildComponent:AfterViewInit");
  }
 
  ngAfterViewChecked() {
    console.log("  ChildComponent:AfterViewChecked");
  }
 
  ngOnDestroy() {
    console.log("  ChildComponent:ngOnDestroy");
  }
 
}
 
 
  • 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
import { ChangeDetectionStrategy, Component, Input,  OnInit } from '@angular/core';
import { Customer } from './customer';
 
@Component({
  selector: 'app-grand-child',
  changeDetection:ChangeDetectionStrategy.Default,
  template: `
  
      <h3>grand child component </h3>
 
      <br>
      Name {{customer.name}}
  
  `,
})
export class GrandChildComponent {
 
 
  @Input() customer:Customer
  
  constructor() {
    console.log("    GrandChildComponent:Contructed");
  }
 
  ngOnChanges() {
    console.log("    GrandChildComponent:ngOnChanges");
  }
 
  ngOnInit() {
    console.log("    GrandChildComponent:ngOnInit");
  }
 
 
  ngDoCheck() {
    console.log("    GrandChildComponent:DoCheck");
  }
 
  ngAfterContentInit() {
    console.log("    GrandChildComponent:ngAfterContentInit");
  }
 
  ngAfterContentChecked() {
    console.log("    GrandChildComponent:AfterContentChecked");
  }
 
  ngAfterViewInit() {
    console.log("    GrandChildComponent:AfterViewInit");
  }
 
  ngAfterViewChecked() {
    console.log("    GrandChildComponent:AfterViewChecked");
  }
 
  ngOnDestroy() {
    console.log("    GrandChildComponent:ngOnDestroy");
  }
 
 
 
}
 
  • 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

댓글