Advertisement
Beginner Angular, Content Projection (ng-content)

What is a simple real world example of when content projection is useful?

Short answer

A reusable alert box component can use content projection to display any message passed into it, whether that message is plain text, a link, or even another small component, without the alert box itself needing to know exactly what kind of content it will ever display.

Save Angular mock interview
Advertisement
AModel answer
A reusable alert box component can use content projection to display any message passed into it, whether that message is plain text, a link, or even another small component, without the alert box itself needing to know exactly what kind of content it will ever display.
@Component({
  selector: 'app-alert',
  template: `
    <div class="alert">
      <ng-content></ng-content>
    </div>
  `
})
export class AlertComponent {}

// Used differently in different places:
// <app-alert>Simple text message</app-alert>
// <app-alert><a href="/help">Need help? Click here</a></app-alert>
Real-world example
A website reuses the same AlertComponent to show a simple error message on one page and a message with a clickable link on another, thanks to content projection letting each usage supply completely different content.
Likely follow-ups
  • How is content projection different from simply passing a string as a regular input?
  • Can content projection be combined with conditional rendering, like the new at if syntax?
Related topics