Content Projection & Templates

🅰️ Angular Lesson 14 Advanced

Content projection allows you to inject custom HTML content into component templates dynamically, enabling the creation of highly reusable UI layouts.

1 ng-content projection selectors

Angular provides specific features for projection layouts:

  • <ng-content>: A placeholder tag that injects content passed from parent components directly into the child template.
  • Select Projection: Projects specific content based on CSS selectors or element tags: <ng-content select=".card-body"></ng-content>.
2 Card Template Projection Setup

Let's check how to build a flexible card component:

HTML — Card Template
<!-- Project header contents --> <ng-content select="[card-header]"></ng-content>
<!-- Project default body contents --> <ng-content></ng-content>

Parents can project custom layouts into these placeholders:

HTML — Parent Usage Layout
<app-card>
  <h1 card-header>Featured Article</h1>
  <p>This body paragraph is projected into the default card body section.</p>
</app-card>
3 Code Challenge
Challenge: Write a custom alert dialog box component that uses content projection to inject custom body message layouts, and style it with color schemes based on alert types.