Skip to main content

What does ngAfterViewInit() do? When is it called?

In Angular, ngAfterViewInit() is a lifecycle hook that is called once, after the component's view and all its child components are initialized.

Key points

  1. What it does:
  • Lets you safely work with DOM elements and child components through @ViewChild or @ViewChildren.
  • Used to run logic that depends on the component and its child elements being fully rendered.
  1. When it is called:
  • Once, after the view is first initialized.
  • After ngAfterContentInit() and before the first ngAfterViewChecked() check.

Example:

ts
export class MyComponent implements AfterViewInit { @ViewChild('myInput') input: ElementRef; ngAfterViewInit() { this.input.nativeElement.focus(); // safe to access the DOM console.log('Component view and child components initialized'); } }
  • At this point, all template elements and child components are already created and available.

In other words, ngAfterViewInit is a hook for working with the DOM and child components after they are fully initialized.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.