What Is AfterViewInit in Angular?
The AfterViewInit () is a lifecycle hook that is
invoked when the component’s view has been fully initialized. The
ngAfterViewInit() method is used to handle any additional initialization tasks.
The AfterViewInit() is called once after
ngAfterContentChecked.
The ngAfterViewInit() is the method of
AfterViewInit interface.
The AfterViewInit interface code from Angular doc
and its look like,
interface AfterViewInit {
ngAfterViewInit(): void
}
The ngAfterViewInit() method calls after it
creates a component's child views.
A callback method that is invoked immediately
after Angular has completed initialization of a component's view.
The ngAfterViewInit() method invoked only once
when the view is instantiated.
Example,
@Component({
selector: 'my-app',
template: `<h3>ngAfterViewInit() Demo</h3>`
})
class MyDemoComponent implements AfterViewInit {
ngAfterViewInit() {
console.log("---ngAfterViewInit() My Demo App---");
}
}
Note - The ngAfterViewInit() is used to access
properties annotated with @ViewChild() and @ViewChildren() decorators.
Another
example to understand the Angular lifecycle Hook,
import { Component } from '@angular/core';
@Component({
selector: 'angular-lifecycle-hook',
template: `<h3>Lifecycle Hook Demo</h3>
`
})
export class LifecycleHookComponent {
constructor() {
console.log("constructor");
}
ngOnInit() {
console.log("Inside ngOnInit");
}
ngDoCheck() {
console.log("Inside ngDoCheck");
}
ngAfterContentInit() {
console.log("nside ngAfterContentInit");
}
ngAfterContentChecked() {
console.log("Inside ngAfterContentChecked");
}
ngAfterViewInit() {
console.log("Inside ngAfterViewInit");
}
ngAfterViewChecked() {
console.log("Inside ngAfterViewChecked");
}
ngOnDestroy() {
console.log("Inside ngOnDestroy");
}
}
The output -
o
constructor
o
Inside ngOnInit
o
Inside ngDoCheck
o
Inside ngAfterContentInit
o
Inside ngAfterContentChecked
o
Inside ngAfterViewInit
o
Inside ngAfterViewChecked