Blog

ngAfterViewInit Example | Angular

Key Takeaways

  • ngAfterViewInit is a lifecycle hook called once after Angular has fully initialized the component's view.
  • It's particularly useful for DOM manipulation and accessing view children.
  • Changes in the component's view do not trigger ngAfterViewInit again.

Angular's lifecycle hooks provide controls over different phases of you component's lifespan. One of the critical hooks in this lifecycle is ngAfterViewInit. Understanding when to use it can significantly enhance how you manage your component's behavior, especially when interacting with the DOM.

import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-home',
  template: `
Initial Text
`, styleUrls: ['./home.component.css'] }) export class HomeComponent implements AfterViewInit { @ViewChild('myDiv') myDiv: ElementRef; ngAfterViewInit() { this.myDiv.nativeElement.textContent = "Text after view init"; console.log("after view init"); } }

The example above highlights how ngAfterViewInit is used to manipulate a DOM element after its view has been fully initialized. By using @ViewChild, you gain access to the desired DOM element once Angular has done its initial renders. This pattern is optimal for DOM manipulations that are sensitive to the timing of template rendering.

ngAfterViewInit() is particularly useful for operations such as initializing third-party libraries dependent on DOM elements or performing complex animations.

When should you use ngAfterViewInit?

ngAfterViewInit is beneficial for accessing ViewChild properties, initializing external libraries, or performing checks and manipulations that require the view to be fully rendered. This ensures your operations are performed on an accurate state of the DOM, avoiding issues with incomplete view renderings.

FAQ

Does ngAfterViewInit run every time data changes?

No, ngAfterViewInit runs only once after the view is initialized. Subsequent changes in the data or state of a component do not trigger it again.

How does ngAfterViewInit differ from ngOnInit?

ngOnInit runs once the component has been initialized but before the view is rendered. In contrast, ngAfterViewInit runs after the view and all of its children have been fully initialized and checked.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews