What is ngAfterViewInit in Angular: Explained with Example
ngAfterViewInit is an Angular lifecycle hook method that runs after Angular fully initializes a component's view and its child views. It is used to perform actions that require the component's template elements to be fully rendered and accessible.How It Works
Think of ngAfterViewInit as a moment when Angular says, "Okay, the component's HTML and all its child components are ready and visible on the screen." Before this, the component's view might not be fully set up, so trying to access or manipulate elements could fail.
This hook runs once after the component's view initialization is complete. It is like waiting for a cake to finish baking before you decorate it. You can't add the final touches until the cake is fully baked and cooled.
Example
This example shows a component that uses ngAfterViewInit to access a paragraph element after the view is ready and changes its text color.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-sample', template: `<p #paraRef>This text will change color after view init.</p>` }) export class SampleComponent implements AfterViewInit { @ViewChild('paraRef') paragraph!: ElementRef<HTMLParagraphElement>; ngAfterViewInit() { this.paragraph.nativeElement.style.color = 'blue'; } }
When to Use
Use ngAfterViewInit when you need to work with the component's template elements or child components after they are fully loaded. For example:
- Manipulating DOM elements directly (like changing styles or focusing inputs)
- Calling methods on child components accessed via
@ViewChild - Starting animations that require the view to be ready
It is not suitable for data fetching or logic that does not depend on the view.
Key Points
ngAfterViewInitruns once after the component's view and child views are initialized.- It is part of Angular's lifecycle hooks and requires implementing the
AfterViewInitinterface. - Useful for DOM access and child component interaction after rendering.
- Do not use it for data loading or logic unrelated to the view.
Key Takeaways
ngAfterViewInit runs after the component's view is fully initialized and rendered.AfterViewInit interface to use this hook.