Friday, June 18, 2021

ngAfterViewInit()

 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.

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.

ngAfterViewInit can be used with @ViewChild() and @ViewChildren() properties. ngAfterContentInit() can be used with @ContentChild and @ContentChildren properties.

Example

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.


No comments:

Followers

Link