0
0
Angularframework~5 mins

ngAfterViewInit for view ready in Angular

Choose your learning style9 modes available
Introduction

ngAfterViewInit runs code after the component's view is fully loaded. It helps you work with elements or child components safely.

You want to access or change HTML elements after they appear on screen.
You need to call a method on a child component after it is ready.
You want to start animations or measurements that require the view to be visible.
You want to set focus on an input field after the page loads.
Syntax
Angular
import { AfterViewInit } from '@angular/core';

export class YourComponent implements AfterViewInit {
  ngAfterViewInit() {
    // code to run after view is ready
  }
}

ngAfterViewInit is a lifecycle hook method Angular calls once after the view is initialized.

Implement the AfterViewInit interface to use this hook.

Examples
Simple example logging a message when the view is ready.
Angular
export class MyComponent implements AfterViewInit {
  ngAfterViewInit() {
    console.log('View is ready!');
  }
}
Focuses an input element after the view loads using @ViewChild.
Angular
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';

export class MyComponent implements AfterViewInit {
  @ViewChild('myInput') input!: ElementRef<HTMLInputElement>;

  ngAfterViewInit() {
    this.input.nativeElement.focus();
  }
}
Sample Program

This component sets focus on the input box after the view is ready. It uses ngAfterViewInit to safely access the input element.

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

@Component({
  selector: 'app-sample',
  template: `
    <input #myInput type="text" placeholder="Type here...">
  `
})
export class SampleComponent implements AfterViewInit {
  @ViewChild('myInput') input!: ElementRef<HTMLInputElement>;

  ngAfterViewInit() {
    this.input.nativeElement.focus();
    console.log('Input is focused after view init');
  }
}
OutputSuccess
Important Notes

Do not try to access view elements in the constructor or ngOnInit; they may not be ready yet.

ngAfterViewInit runs only once after the first view load.

Summary

ngAfterViewInit runs after the component's view is fully loaded.

Use it to safely access or modify view elements and child components.

It helps avoid errors from accessing elements too early.