AfterViewInit in Angular

AfterViewInit in Angular – Lifecycle Hook

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

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^