Back to results for “Lifecycle Hooks”
Angular › Content Projection (ng-content)

How would you check whether any content was actually projected into a component using ng-content?

Intermediate

Answer

You can use the ContentChild decorator to get a reference to projected content, and check whether it exists after the view has initialized, letting you conditionally render fallback content or adjust your component's layout depending on whether real content was actually provided.
@Component({
  selector: 'app-card',
  template: `
    <ng-content></ng-content>
    @if (!hasContent) {
      <p>No content provided</p>
    }
  `
})
export class CardComponent implements AfterContentInit {
  @ContentChild('content') content: any;
  hasContent = false;
  ngAfterContentInit() { this.hasContent = !!this.content; }
}
Real-world example A reusable card component shows a friendly placeholder message automatically whenever it is used without any content actually being provided inside it, checking for this using ContentChild after the view initializes.

Common follow-ups: Why must this check happen inside ngAfterContentInit rather than earlier lifecycle hooks?;What is the difference between ContentChild and ViewChild?