How to use @ContentChild in Angular
Using @ContentChild decorator enables access to projected content elements and components passed through ng-content for dynamic manipulation and interaction. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented @ContentChild in countless Angular components for card headers, modal content, and flexible layout systems. From my expertise, the most effective approach is using @ContentChild with template reference variables to access projected content. This method provides direct control over content projection and enables advanced component composition patterns.
Use @ContentChild
decorator with template reference variables to access projected content elements.
// wrapper.component.ts
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'
@Component({
selector: 'app-wrapper',
template: `
<div class="wrapper">
<h2>Wrapper Component</h2>
<div class="content">
<ng-content></ng-content>
</div>
<button (click)="highlightContent()">Highlight Content</button>
</div>
`
})
export class WrapperComponent implements AfterContentInit {
@ContentChild('contentRef') contentElement!: ElementRef<HTMLElement>
ngAfterContentInit() {
// Access projected content after content initialization
if (this.contentElement) {
console.log('Projected content:', this.contentElement.nativeElement)
}
}
highlightContent() {
if (this.contentElement) {
this.contentElement.nativeElement.style.backgroundColor = 'yellow'
}
}
}
// Usage in parent template
@Component({
template: `
<app-wrapper>
<p #contentRef>This content will be projected and can be accessed!</p>
</app-wrapper>
`
})
export class ParentComponent { }
The @ContentChild decorator queries projected content for elements matching the specified selector. Use ng-content for content projection and template reference variables to mark projected elements. Access ContentChild references in ngAfterContentInit lifecycle hook when projected content is initialized.
Best Practice Note:
This is the same @ContentChild approach we use in CoreUI Angular components for flexible card and panel layouts. Always implement AfterContentInit interface and check if ContentChild references exist before accessing them to handle optional projected content.