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: `
`,
})
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: ` Here is the user name: {{ user.name }}`,
})
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
- ngAfterViewInit is executed just after ngAfterContentChecked
- ngAfterViewInit is executed when the component and child component are fully initialized
- ngAfterViewInit is executed only once
- ngAfterViewInit can't detect the data-bound changes of the child components ( ngAfterViewChecked can do that )
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:
- How to use ngAfterViewInit lifecycle hook ?
- How to use ngOnChanges lifecycle hook ?
- How to use ngOnInit lifecycle hook ?
- How to use ngDoCheck lifecycle hook in angular ?
- How to use ngAfterContentInit lifecycle hook ?
- How to use ngAfterContentChecked lifecycle hook ?
- How to use ngAfterViewChecked lifecycle hook ?
- How to use ngOnDestroy lifecycle hook ?
3 comments
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
Just go to your tsconfig.json and add this line :
“strictPropertyInitialization”: false
Yes, i already found the solution, I modified the tsconfig.json and added strictPropertyInitialization = false, exactly like you said. thank u
Comments are closed.