Home Angular Tutorials Angular ngAfterViewInit lifecycle hook

Angular ngAfterViewInit lifecycle hook

by aouidane.med.amine
56,195 views 15 min read

In this tutorial, we will learn the ngAfterViewInit lifecycle hook in angular, we will also see how and when we use it through a basic example step by step.

Table of Contents

Angular Lifecycle Hooks

Angular has 8 lifecycle hooks, but in this tutorial, we will cover only the ngAfterViewInit lifecycle hook.

ngAfterViewInit lifecycle hook Syntax and usage note

				
					@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements AfterViewInit {
  ngAfterViewInit() {
    // ...
  }
}
				
			

Source : angular.io

What is ngAfterViewInit lifecycle hook in Angular ?

The ngAfterViewInit lifecycle hook in angular is a simple function callback that is called after angular has completely initialized the component view and child view.

The ngAfterViewInit is invoked only once, so if there is any modification in the data-bound after the initialization of the component, we couldn’t detect that through the ngAfterViewInit lifecycle hook.

To do that we need to use other lifecyle hooks such as ngDoCheck and ngOnChanges ( note that the ngOnchange has some limitations because it uses the property reference to check the difference, so it can’t detect the changes if you update the object property, or you push something in an array)

The ngAfterViewInit invoked  immediately after the callback of the ngAfterContentChecked lifeCycle hook ( invoked after angular checks the content projection) 

the ngAfterViewInit lifecycle hook is also used if we want to be notified when the child component is fully initialized. So we can access for example to the child component using @ViewChild() or @ViewChildren() without getting any problem.

How to use ngAfterViewInit lifecycle hook in Angular ?

To explain how the ngAfterViewInit works, we will create a simple application by creating two components, and we will try to access to the child component through the callback of the ngAfterViewInit and the ngOnInit lifecycle hook in the same time to see the difference between them and understand the purpose of using  ngAfterViewInit lifecycle hook.

First, we will create a parent component where we implement the ngAfterViewInit and ngOnInit interfaces.

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

import { ChildComponent } from './child-component/child.component';
@Component({
  selector: 'app-root',
     template: `
       <app-child></app-child>
   `,
})
export class ParentComponent implements OnInit, AfterViewInit {
  
  @ViewChild(ChildComponent) childComp : ChildComponent;

  ngOnInit() {
        console.log('[ngOnInit] user name : ' + this.childComp?.getName());
  }
  
  ngAfterViewInit() {
        console.log('[ngAfterViewInit] user name : ' + this.childComp?.getName());
  }
  }
}

				
			

Now we will create the child component and implement a simple function that returning a string.

Then we will try to access to that function from the parent and get the response.

				
					import { Component, OnInit} from '@angular/core';
@Component({
  selector: 'app-child',
  template: `<div> Here is the user name: {{ user.name }}</div>`,
})
export class ChildComponent implements OnInit {
  public user: any

  ngOnInit(){
   // we initialize the user name
   this.user = {
   name : 'XpertTuto.com'
   }
  }
  
  public getName(): string{
  return this.user.name;
  }
}

				
			

Now if we run our angular application and check the console log, we will see the following output : 

[ngOnInit] user name : undefined 

[ngAfterViewInit] user name : XperTuto.com

As you see we can’t access to the child content through the ngOnInit lifecycle hook because it is executed before the ngAfterContentChecked lifecycle hook

That means the child component is not yet fully initialized, that’s why we use the ngAfterViewInit to access to the content of the child component, because it is executed immediately after the ngAfterContentChecked,

That means, we have access to a fully initialized component.

Recapitulation

In this tutorial we have seen multiples use cases of ngAfterViewInit lifecycle hook in Angular also we have seen the difference between the ngAfterViewInit and the ngOnInit lifecycle hook to understand exactly when the callback is executed to avoid any confusion between them.

Clone and Run the project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/ngAfterViewInit_lifecyle_hook.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Lifecycle hooks:

You may also like

3 comments

rony dutrok July 8, 2022 - 1:26 pm

Hello, I was following the example of the tutorial, but I have a compilation error : Property ‘childComp’ has no initializer and is not definitely assigned in the constructor

aouidane.med.amine July 8, 2022 - 3:13 pm

Just go to your tsconfig.json and add this line :

“strictPropertyInitialization”: false

RONY DUTROK July 8, 2022 - 3:20 pm

Yes, i already found the solution, I modified the tsconfig.json and added strictPropertyInitialization = false, exactly like you said. thank u

Comments are closed.