typescript 40 lines · 7 steps

Multi-slot content projection in Angular

An Angular card component distributes projected markup into named slots using ng-content selectors.

Explained by highlit
1import { Component, ChangeDetectionStrategy } from '@angular/core';
2 
3@Component({
4 selector: 'app-card',
5 standalone: true,
6 changeDetection: ChangeDetectionStrategy.OnPush,
7 template: `
8 <article class="card">
9 <header class="card__header">
10 <ng-content select="[card-title]">
11 <span class="card__title--fallback">Untitled</span>
12 </ng-content>
13 <div class="card__actions">
14 <ng-content select="[card-actions]"></ng-content>
15 </div>
16 </header>
17 
18 <div class="card__media">
19 <ng-content select="img, video, [card-media]"></ng-content>
20 </div>
21 
22 <div class="card__body">
23 <ng-content></ng-content>
24 </div>
25 
26 <footer class="card__footer">
27 <ng-content select="card-footer"></ng-content>
28 </footer>
29 </article>
30 `,
31 styles: [`
32 .card { display: flex; flex-direction: column; border: 1px solid #e2e2e2; border-radius: 12px; overflow: hidden; }
33 .card__header { display: flex; align-items: center; justify-content: space-between; padding: 1rem; }
34 .card__media img, .card__media video { width: 100%; display: block; }
35 .card__body { padding: 1rem; }
36 .card__footer:empty { display: none; }
37 .card__footer { padding: 0.75rem 1rem; border-top: 1px solid #f0f0f0; }
38 `],
39})
40export class CardComponent {}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Multiple ng-content elements with select attributes let one component route projected content into distinct regions.
  2. 2Fallback content inside ng-content renders only when nothing matches that slot, giving sensible defaults.
  3. 3OnPush change detection plus a purely presentational template makes a component that only re-renders when inputs or projection change.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Multi-slot content projection in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code