Angular ngAfterViewInit()

By Arvind Rai, February 13, 2024
Angular ngAfterViewInit() is the method of AfterViewInit interface. ngAfterViewInit() is a lifecycle hook that is called after Angular has fully initialized a component's views. ngAfterViewInit() is used to handle any additional initialization tasks. Find the AfterViewInit interface code from Angular doc.
interface AfterViewInit {
  ngAfterViewInit(): void
} 
ngAfterViewInit() is used to access properties annotated with @ViewChild() and @ViewChildren() decorators. Here on this page we will discuss ngAfterViewInit() lifecycle hook with examples.

Using ngAfterViewInit()

Find the simple example that uses ngAfterViewInit() lifecycle hook.
afterviewinit-demo.component.ts
import { Component, AfterViewInit } from '@angular/core';

@Component({
   selector: 'app-afterviewinit',
   template: `
     <h3>ngAfterViewInit() Demo</h3>
    `
})
export class AfterViewInitDemoComponent implements AfterViewInit { 
  ngAfterViewInit() {
    console.log("---ngAfterViewInit() Demo---");
  }
} 
It is optional to implement AfterViewInit interface. Angular looks for only ngAfterViewInit() method name to run this lifecycle hook. Implementing interfaces are optional because JavaScript language doesn't have interfaces and Angular can't see TypeScript interfaces at runtime because they disappear from the transpiled JavaScript. But it is good practice to add interfaces to TypeScript directive classes in order to benefit from strong typing and editor tooling.

ngAfterViewInit() in Angular Lifecycle Hooks

ngAfterViewInit() is executed after Angular initializes the component's views and child views. The child view is the view that a directive is in. ngAfterViewInit() is executed only once after the first call of ngAfterContentChecked() life cycle hook. After ngAfterViewInit() lifecycle hook, the ngAfterViewChecked() is called. ngAfterContentChecked() responds after Angular checks the content projected into the directive/component and ngAfterViewChecked() responds after Angular checks the component's views and child views.
Find the complete lifecycle hooks of angular and their sequences to execute.
lifecycle-hook.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-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("---Inside ngAfterContentInit---");
  }
  ngAfterContentChecked() {
    console.log("---Inside ngAfterContentChecked---");
  }
  ngAfterViewInit() {
    console.log("---Inside ngAfterViewInit---");
  }  
  ngAfterViewChecked() {
    console.log("---Inside ngAfterViewChecked---");    
  }
  ngOnDestroy() {
    console.log("---Inside ngOnDestroy---");      
  }
} 
Find the output in console.
---constructor--- 
---Inside ngOnInit--- 
---Inside ngDoCheck---
---Inside ngAfterContentInit---
---Inside ngAfterContentChecked---
---Inside ngAfterViewInit---
---Inside ngAfterViewChecked--- 
ngAfterViewInit can be used with @ViewChild() and @ViewChildren() properties. ngAfterContentInit() can be used with @ContentChild and @ContentChildren properties. Angular has one more lifecycle hook i.e. ngOnChanges() which responds when Angular sets or resets data-bound @Input() properties.

ngAfterViewInit() Example with @ViewChild() and @ViewChildren()

Here we will create a demo in which ngAfterViewInit() will access @ViewChild() and @ViewChildren() properties in our component.
message.directive.ts
import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
    selector: '[cpMsg]'
})
export class MessageDirective {
    constructor(public viewContainerRef: ViewContainerRef) { }
} 
message.component.ts
import { Component, ViewChild, ViewChildren, AfterViewInit, TemplateRef, QueryList } from '@angular/core';
import { MessageDirective } from './message.directive';

@Component({
    selector: 'app-message',
    template: `
    <h3>@ViewChildren() and @ViewChild()</h3>
	<div cpMsg></div>
	<div cpMsg></div>
	<div cpMsg></div>	
		
	<ng-template #msgTemp>
          Namaste!
	</ng-template>
   `
})
export class MessageComponent implements AfterViewInit {
	@ViewChildren(MessageDirective)
	private msgList: QueryList<MessageDirective>;

	@ViewChild('msgTemp')
	private msgTempRef: TemplateRef<any>;

	ngAfterViewInit() {
                console.log("this.msgList.length: " + this.msgList.length);
        
		this.msgList.forEach(messageDirective =>
			messageDirective.viewContainerRef.createEmbeddedView(this.msgTempRef));
	}
} 
As we know that ngAfterViewInit() responds when the component's view and its child view is initialized, so here inside this method we are reading the msgTemp template data and embedding it into the cpMsg directive.
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
    <app-afterviewinit></app-afterviewinit>
    <app-lifecycle-hook></app-lifecycle-hook>
    <app-message></app-message>
   `
})
export class AppComponent { 
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { AfterViewInitDemoComponent } from './afterviewinit-demo.component';
import { LifecycleHookComponent } from './lifecycle-hook.component';
import { MessageComponent } from './message.component';
import { MessageDirective } from './message.directive';

@NgModule({
  imports: [     
      BrowserModule,
  ],
  declarations: [
      AppComponent,
      AfterViewInitDemoComponent,
      LifecycleHookComponent,
      MessageComponent,
      MessageDirective
  ],
  providers: [
  ],
  bootstrap: [
      AppComponent
  ]
})
export class AppModule { } 

Output

Find the print-screen of the output.
Angular ngAfterViewInit()

References

Angular AfterViewInit
Angular Lifecycle Hooks

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us