How to use ngAfterContentInit in Angular

Working with projected content and content children requires knowing when they are fully initialized and available for interaction. 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 built numerous components that use content projection for flexible layouts and reusable designs. The most effective approach is using the ngAfterContentInit lifecycle hook, which ensures that all projected content and content children are properly initialized and queryable. This hook is crucial for components that need to interact with or configure projected content.

Implement ngAfterContentInit to safely access projected content and content children after they are initialized.

import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'

@Component({
  selector: 'app-card',
  template: '<div class="card"><ng-content></ng-content></div>'
})
export class CardComponent implements AfterContentInit {
  @ContentChild('cardTitle') titleElement!: ElementRef

  ngAfterContentInit() {
    if (this.titleElement) {
      this.titleElement.nativeElement.classList.add('highlighted')
    }
  }
}

The ngAfterContentInit hook is called after Angular has projected external content into the component’s view and initialized all content children. At this point, all @ContentChild and @ContentChildren queries are resolved and ready for use. This lifecycle hook is essential when your component needs to interact with or modify projected content, such as adding CSS classes, setting up event listeners, or configuring nested components.

Best Practice Note:

This is the approach we use in CoreUI Angular components for handling flexible content layouts and customizable component designs. This hook is called only once per component, making it ideal for one-time setup of projected content rather than ongoing content monitoring.


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