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
- What it does:
- Lets you safely work with DOM elements and child components through
@ViewChildor@ViewChildren. - Used to run logic that depends on the component and its child elements being fully rendered.
- When it is called:
- Once, after the view is first initialized.
- After
ngAfterContentInit()and before the firstngAfterViewChecked()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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.