How to use ngAfterViewInit in Angular

Accessing child components and DOM elements after the view has been fully initialized is a common requirement in Angular applications. As the creator of CoreUI, a widely used open-source UI library, and with over 11 years of experience in software development including Angular since 2014, I’ve implemented countless components that need to interact with child elements after rendering. The most effective approach is using the ngAfterViewInit lifecycle hook, which guarantees that all view children are available and properly initialized. This hook is essential for any operations that depend on the complete view hierarchy being ready.

Implement ngAfterViewInit to safely access child components and DOM elements after view initialization completes.

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

@Component({
  selector: 'app-example',
  template: '<input #inputRef type="text">'
})
export class ExampleComponent implements AfterViewInit {
  @ViewChild('inputRef') inputElement!: ElementRef

  ngAfterViewInit() {
    this.inputElement.nativeElement.focus()
  }
}

The ngAfterViewInit hook is called after Angular has fully initialized the component’s view and all its child views. At this point, all @ViewChild and @ViewChildren queries are resolved and available for use. This lifecycle hook is perfect for DOM manipulation, setting up third-party libraries that need DOM elements, or configuring child components that require the parent view to be ready.

Best Practice Note:

This is the approach we use in CoreUI Angular components for initializing complex UI widgets that depend on DOM elements. Remember that this hook is called only once per component lifetime, so use it for one-time initialization tasks rather than ongoing view updates.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What are the three dots `...` in JavaScript do?
What are the three dots `...` in JavaScript do?

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to dynamically add, remove, and toggle CSS classes in React.js
How to dynamically add, remove, and toggle CSS classes in React.js

Answers by CoreUI Core Team