A card or a panel draws the frame, and the parent decides what goes inside. This part covers ng-content, named slots with select, fallback content, ng-template, ngTemplateOutlet and a list that takes a row template.
Many components are a frame around something else. A card has a border, a title and some buttons. A dialog has a backdrop and a close button. A panel opens and closes. The frame is always the same, but what goes inside changes every time you use it. Inputs from Part 5 are good for a title string. They’re a poor fit for a body with a paragraph, a list and a button with its own click handler.
This part covers content projection: the parent writes markup between a component’s tags, and the child decides where it goes. We cover <ng-content />, several slots with select, fallback content, ngProjectAs, and the trap of hiding projected content with @if. Then we cover <ng-template> and ngTemplateOutlet, which render content only when needed and can render it once per item. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
Try this first
This example has two files. Make src/app/box.ts and paste the first one. Paste the second into src/app/app.ts.
// src/app/box.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-box',
template: `
<p>Box start</p>
<p>Box end</p>
`,
})
export class Box {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Box } from './box';
@Component({
selector: 'app-root',
imports: [Box],
template: `
<app-box>
<p>Hello from App</p>
</app-box>
`,
})
export class App {}
Until now we’ve always closed a component tag straight away, as in <app-product-card />. Here App puts a paragraph between <app-box> and </app-box>.
Before you read on, guess. Where does “Hello from App” show up on the page? Before the box, after it, or somewhere else?
Here’s what happens. The page shows:
Box start
Box end
It doesn’t show up at all. There’s no build error and no warning in the console. Angular made the paragraph, but it never put it on the page, because Box never said where it goes.
ng-content: a hole the parent fills
<ng-content /> in a child’s template marks the spot where the parent’s content goes. Add it to Box:
// src/app/box.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-box',
template: `
<p>Box start</p>
<ng-content />
<p>Box end</p>
`,
})
export class Box {}
Keep app.ts as it was. Now the page shows:
Box start
Hello from App
Box end
The content between the parent’s tags is called projected content, and <ng-content /> is where it’s projected to. Think of a film projector: the picture is made in one place and shows up somewhere else.
<ng-content /> isn’t an element on the page. Angular replaces it with the content. The rendered HTML is just the three paragraphs inside <app-box>:
<app-box><p>Box start</p><p>Hello from App</p><p>Box end</p></app-box>
(Angular adds a few attributes of its own; we left them out.) The child doesn’t need an input, and it doesn’t need to know what the content is. That’s the point: Box is the frame, and every parent that uses it decides what goes in the frame.
Projected content belongs to the parent
The content sits inside the child on the page, but it’s still part of the parent’s template. Its bindings read the parent’s signals, and its event handlers call the parent’s methods:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Box } from './box';
@Component({
selector: 'app-root',
imports: [Box],
template: `
<app-box>
<p>Likes: {{ likes() }}</p>
<button (click)="like()">Like</button>
</app-box>
`,
})
export class App {
protected readonly likes = signal(0);
protected like() {
this.likes.update((n) => n + 1);
}
}
Click Like twice. The page shows:
Box start
Likes: 2
Like
Box end
Box has no likes and no like(). It never sees them. likes() is read and like() is called in App, because that’s whose template they’re written in. This is different from passing data down with an input. Here the child doesn’t get a value at all. It just gives the parent’s markup a place to sit.
Styles mostly follow the same rule. A rule in App‘s styles that targets the paragraph applies to it. A rule in Box‘s styles, like p { font-weight: bold; }, doesn’t, even though the paragraph sits inside Box‘s template on the page. One exception: properties that HTML passes from an element to the elements inside it, like color and font-family, still flow in from the box’s elements, as they would on any page. (We checked all three in the browser.) Part 7 explains how Angular scopes component styles, which is why this happens.
Several slots with select
A card usually has more than one place for content: a title at the top, the main text in the middle, buttons at the bottom. Give <ng-content> a select attribute, and it only takes the content that matches. Each <ng-content> is then a slot. Make src/app/card.ts:
// src/app/card.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<article>
<header>
<ng-content select="h2" />
<ng-content select="[card-meta]" />
</header>
<ng-content />
<footer><ng-content select=".actions" /></footer>
</article>
`,
})
export class Card {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Card } from './card';
@Component({
selector: 'app-root',
imports: [Card],
template: `
<app-card>
<div class="actions"><button>Buy</button></div>
<h2>Green tea</h2>
<p>A light, grassy tea.</p>
<p card-meta>Japan, 100 g</p>
</app-card>
`,
})
export class App {}
The page shows:
Green tea
Japan, 100 g
A light, grassy tea.
Buy
The value of select is a simple CSS selector. This card uses the three common kinds:
select="h2"matches an element by its tag name.select="[card-meta]"matches an attribute.<p card-meta>has an attribute calledcard-metawith no value, which is enough. An attribute like this is a handy way to label content for a slot, because it doesn’t change how the element looks.select=".actions"matches a class.
You can also list several, separated by commas: select="h4, .note" takes both. That’s about it. Selectors like div h2 or h3:first-child don’t do what they would in a stylesheet: we tried them, the first acted like plain h2 and the second matched nothing, with no error either time. Classes and attributes count only when they’re written plainly in the template. <span [class.actions]="true"> doesn’t match .actions.
The plain <ng-content /> with no select is the default slot. It gets everything that didn’t match another slot. Here that’s the paragraph about the tea.
Look at the order, too. The parent wrote the buttons first and the meta line last. The page shows them in the order of the card’s slots. The child’s template decides where things go and in what order. The parent only decides what they are.
Each piece of content goes to the slot whose select matches it. Whatever matches nothing goes to the default slot.
What select looks at
select only looks at the elements directly between the component’s tags. It doesn’t look inside them. If the parent wraps the title in a <div>, the <div> is what gets matched. It isn’t an h2, so it goes to the default slot, title and all.
There’s one helpful exception. An @if block whose content is a single element is matched by that element. So @if (showTitle()) { <h2>Green tea</h2> } still lands in the h2 slot. We checked both cases.
Content that matches nothing
Without a default slot, content that matches no select is never shown, just like in the first example. Angular still creates it, so a component in it still runs: we put a component that logs in its constructor there, and it logged. There’s no error and no warning. If a paragraph you passed to a card is missing, check the card’s slots first. Exercise 1 is a bug like this.
Fallback content
Sometimes a slot should show something when the parent leaves it empty. Put that between <ng-content> and </ng-content>. It’s called fallback content:
// src/app/card.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<article>
<header>
<ng-content select="h2">
<h2>Untitled</h2>
</ng-content>
</header>
<ng-content />
<footer>
<ng-content select=".actions">No actions</ng-content>
</footer>
</article>
`,
})
export class Card {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Card } from './card';
@Component({
selector: 'app-root',
imports: [Card],
template: `
<app-card>
<h2>Green tea</h2>
<p>A light, grassy tea.</p>
<div class="actions"><button>Buy</button></div>
</app-card>
<app-card>
<p>A card with only a body.</p>
</app-card>
`,
})
export class App {}
The page shows:
Green tea
A light, grassy tea.
Buy
Untitled
A card with only a body.
No actions
The first card filled both slots, so their fallbacks never showed. The second card gave neither an h2 nor an .actions element, so both fallbacks showed. A tag with nothing but spaces and line breaks between its tags, like <app-card> </app-card>, counts as empty too: we tried it, and both fallbacks showed.
Fallback content belongs to the child. It’s written in the child’s template, so it uses the child’s signals and the child’s styles.
ngProjectAs: when the wrapper is the problem
Sometimes the parent needs to wrap content to put more than one element in a slot. The card’s title slot takes an h2. Say the parent wants the title and a small “New” label together. A wrapper <div> won’t match h2.
<ng-container> is an Angular element that groups things in a template but doesn’t add anything to the page. Give it ngProjectAs, and it’s matched as if it were the selector you name:
// src/app/app.ts
import { Component } from '@angular/core';
import { Card } from './card';
@Component({
selector: 'app-root',
imports: [Card],
template: `
<app-card>
<ng-container ngProjectAs="h2">
<h2>Green tea</h2>
<strong>New</strong>
</ng-container>
<p>A light, grassy tea.</p>
</app-card>
`,
})
export class App {}
The page shows:
Green tea
New
A light, grassy tea.
No actions
Both the h2 and the strong went into the title slot, and the fallback “Untitled” didn’t show. You won’t need ngProjectAs often. When you do, it’s usually because a wrapper broke a match that worked before.
The trap: hiding ng-content with @if
Here’s a panel that opens and closes. It puts its <ng-content /> inside an @if, so the content only shows when the panel is open. Make three files. Note logs a line when Angular creates it. The constructor is a method that runs once, when an object is made; Part 10 covers a component’s life in more detail.
// src/app/note.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-note',
template: `<p>A slow, heavy note</p>`,
})
export class Note {
constructor() {
console.log('Note created');
}
}
// src/app/panel.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<button (click)="open.set(!open())">Toggle</button>
@if (open()) {
<ng-content />
}
`,
})
export class Panel {
protected readonly open = signal(false);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Note } from './note';
import { Panel } from './panel';
@Component({
selector: 'app-root',
imports: [Note, Panel],
template: `
<app-panel>
<app-note />
</app-panel>
`,
})
export class App {}
Load the page. The panel is closed, and the page shows only the button:
Toggle
Now look at the console:
Note created
The note was created, even though nobody can see it. Click Toggle three times: open, close, open. The note shows, and the console gets no new lines:
Toggle
A slow, heavy note
Here’s why. Projected content belongs to the parent, so the parent creates it, as part of drawing its own template. That happens whether or not the child ever shows it. The @if in the child only decides whether the already-made content is attached to the page. Closing the panel takes the note off the page, but doesn’t destroy it, and opening it puts the same note back.
For a paragraph, that doesn’t matter. For a component that loads data from a server or draws a chart, it does: it does all its work at page load, for a panel that may never open. The content projection guide on angular.dev warns against putting <ng-content> inside @if, @for or @switch for this reason. The next section shows what to use instead.
ng-template: content that isn’t made yet
<ng-template> holds a piece of template that Angular doesn’t render. It isn’t created and nothing inside it runs. It’s like a recipe: it says how to make something, and you decide when to make it, and how many times.
To render one, you need two things:
- A way to point at it. A template reference variable from Part 2 does that:
<ng-template #details>names itdetails. On an<ng-template>, that name gives you aTemplateRef, Angular’s type for “a template you can render”. - Something that renders it. That’s the
NgTemplateOutletdirective from@angular/common.<ng-container [ngTemplateOutlet]="details" />renders the template right there. A directive is a class that adds behaviour to an element in a template; Part 11 covers writing your own.
Now the parent can hand the panel a template instead of content. The panel takes it as an input and renders it inside its @if. Keep note.ts, and replace the other two:
// src/app/panel.ts
import { NgTemplateOutlet } from '@angular/common';
import { Component, input, signal, TemplateRef } from '@angular/core';
@Component({
selector: 'app-panel',
imports: [NgTemplateOutlet],
template: `
<button (click)="open.set(!open())">Toggle</button>
@if (open()) {
<ng-container [ngTemplateOutlet]="body()" />
}
`,
})
export class Panel {
readonly body = input.required<TemplateRef<unknown>>();
protected readonly open = signal(false);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Note } from './note';
import { Panel } from './panel';
@Component({
selector: 'app-root',
imports: [Note, Panel],
template: `
<app-panel [body]="details" />
<ng-template #details>
<app-note />
</ng-template>
`,
})
export class App {}
A few things to notice:
input.required<TemplateRef<unknown>>()is an input like the ones in Part 5. Its type is “a template”. Theunknownis about what data the template takes; this one takes none. We’ll use it in the list example below.[body]="details"passes the template, not anything made from it.NgTemplateOutletgoes in the panel’simports, like a component would.@ifand@forneed no import because they’re built into the template language.ngTemplateOutletis a directive, so it does.
Load the page. The console is empty this time:
Click Toggle. The note shows, and now it’s created:
Note created
Click Toggle twice more, to close and open again. The console gets another line:
Note created
That’s the other side of the change. Each time the @if shows the template, Angular makes a fresh note, and each time it hides it, the note is destroyed. Anything the note held, like text typed into a field, starts over. Usually that’s what you want from a panel that’s closed. If it isn’t, keep <ng-content /> and hide it with CSS instead.
The template still belongs to the parent, just like projected content. Its bindings read the parent’s signals and use the parent’s styles, wherever the child renders it.
Worked example: a card with header, body and footer
Let’s build a card you’d actually use. It has a title slot, a body, and a footer for buttons. The title and footer have fallbacks. Slots are marked with attributes, card-title and card-footer, so the parent can use any element it likes for each one.
// src/app/card.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
styles: `
article {
border: 1px solid #ccc;
padding: 8px;
margin-bottom: 8px;
}
`,
template: `
<article>
<header>
<ng-content select="[card-title]">Untitled</ng-content>
</header>
<section><ng-content /></section>
<footer>
<ng-content select="[card-footer]">
<small>No actions</small>
</ng-content>
</footer>
</article>
`,
})
export class Card {}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Card } from './card';
@Component({
selector: 'app-root',
imports: [Card],
template: `
<app-card>
<h2 card-title>Green tea</h2>
<p>A light, grassy tea.</p>
<p>In the cart: {{ inCart() }}</p>
<div card-footer>
<button (click)="add()">Add to cart</button>
</div>
</app-card>
<app-card>
<p>Coming soon.</p>
</app-card>
`,
})
export class App {
protected readonly inCart = signal(0);
protected add() {
this.inCart.update((n) => n + 1);
}
}
Click Add to cart. The page shows:
Green tea
A light, grassy tea.
In the cart: 1
Add to cart
Untitled
Coming soon.
No actions
Some things to notice:
- Both paragraphs went to the default slot, in the order the parent wrote them. A slot can take any number of elements.
- The button’s
(click)callsApp‘sadd(), andinCart()isApp‘s signal. The card knows nothing about carts. - The second card gave neither a
card-titlenor acard-footer, so both fallbacks showed. - The border comes from the card’s own
styles. It styles the<article>, which is in the card’s template, so it applies. A card rule likep { ... }wouldn’t reach the paragraphs the parent passed in, though inherited properties likecolorset on the<article>would.
Worked example: a list that takes a row template
A content slot gets one piece of content, once. A list needs the opposite: the same markup once per item, with a different item each time. The list owns the loop. The parent wants to decide how one row looks. A template input does both.
Make src/app/list.ts:
// src/app/list.ts
import { NgTemplateOutlet } from '@angular/common';
import { Component, input, TemplateRef } from '@angular/core';
export interface RowContext<T> {
$implicit: T;
index: number;
}
@Component({
selector: 'app-list',
imports: [NgTemplateOutlet],
template: `
<ul>
@for (item of items(); track $index) {
<li>
<ng-container
[ngTemplateOutlet]="row()"
[ngTemplateOutletContext]="{ $implicit: item, index: $index }"
/>
</li>
} @empty {
<li>Nothing here yet.</li>
}
</ul>
`,
})
export class List<T> {
readonly items = input.required<T[]>();
readonly row = input.required<TemplateRef<RowContext<T>>>();
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { List } from './list';
interface Book {
title: string;
author: string;
}
@Component({
selector: 'app-root',
imports: [List],
template: `
<app-list [items]="books()" [row]="bookRow" />
<ng-template #bookRow let-book let-i="index">
{{ i + 1 }}. <strong>{{ book.title }}</strong> by {{ book.author }}
</ng-template>
<button (click)="addBook()">Add a book</button>
`,
})
export class App {
protected readonly books = signal<Book[]>([
{ title: 'Dune', author: 'Frank Herbert' },
{ title: 'Emma', author: 'Jane Austen' },
]);
protected addBook() {
this.books.update((list) => [...list, { title: 'Kindred', author: 'Octavia E. Butler' }]);
}
}
Click Add a book. The page shows:
1. Dune by Frank Herbert
2. Emma by Jane Austen
3. Kindred by Octavia E. Butler
Add a book
There’s a lot in a few lines, so let’s take it in pieces.
The context. Each time ngTemplateOutlet renders the template, [ngTemplateOutletContext] hands it an object of values. This is the context. Here it’s { $implicit: item, index: $index }: the current item, and its position from @for (Part 4).
let- reads the context. On the parent’s <ng-template>, let-book makes a variable book that holds the context’s $implicit value. let-i="index" makes a variable i that holds the context’s index. The names on the left are the parent’s choice. $implicit is the one value you get without naming a key, so put the main value there.
The generic. List<T> is a generic class, like signal<T> in Part 3. T stands for “the type of one item”. Angular works it out from what the parent binds: [items]="books()" is a Book[], so here T is Book. The same List works for books, users or anything else.
The typed context. TemplateRef<RowContext<T>> says what context this template gets. Angular checks the list’s [ngTemplateOutletContext] against it, so the list can’t forget a value it promised. The next worked example shows that check catching a mistake.
@empty from Part 4 shows a line when the list has no items. The list owns that, so every parent gets it for free.
The parent’s side has one gap. Angular doesn’t connect the parent’s let-book to RowContext<Book>, so book has the type any, a TypeScript type that switches checking off. We tried {{ book.titel }}: it built without a word and showed nothing where the title should be. Check the row with your eyes the first time it renders.
Worked example: reading two errors
A teammate copies the list into another project. They leave out the NgTemplateOutlet import, and while they’re at it, they drop index from the context, because their rows don’t number themselves:
// src/app/list.ts
import { Component, input, TemplateRef } from '@angular/core';
export interface RowContext<T> {
$implicit: T;
index: number;
}
@Component({
selector: 'app-list',
template: `
<ul>
@for (item of items(); track $index) {
<li>
<ng-container
[ngTemplateOutlet]="row()"
[ngTemplateOutletContext]="{ $implicit: item }"
/>
</li>
}
</ul>
`,
})
export class List<T> {
readonly items = input.required<T[]>();
readonly row = input.required<TemplateRef<RowContext<T>>>();
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { List } from './list';
@Component({
selector: 'app-root',
imports: [List],
template: `
<app-list [items]="names()" [row]="nameRow" />
<ng-template #nameRow let-name>{{ name }}</ng-template>
`,
})
export class App {
protected readonly names = signal(['Ana', 'Ben']);
}
ng serve prints two errors:
✘ [ERROR] NG8002: Can't bind to 'ngTemplateOutlet' since it isn't a known property of 'ng-container'.
1. If 'ngTemplateOutlet' is an Angular directive, then add 'CommonModule' to the '@Component.imports' of this component.
✘ [ERROR] NG8002: Can't bind to 'ngTemplateOutletContext' since it isn't a known property of 'ng-container'.
Read them piece by piece:
- NG8002 is the code we met in Part 5 for a typo in an input name. It means “nothing on this element has a property with that name”.
<ng-container>has no properties of its own.ngTemplateOutletandngTemplateOutletContextare inputs of theNgTemplateOutletdirective, and the directive isn’t in this component’simports, so Angular doesn’t know about them. - The hint suggests
CommonModule. That works, becauseCommonModuleis an older bundle that includesNgTemplateOutletand many other directives. Import just the one you use:NgTemplateOutletfrom@angular/common.
Add the import and build again. Now TypeScript can see the directive’s input types, and the second mistake shows up:
// src/app/list.ts
import { NgTemplateOutlet } from '@angular/common';
import { Component, input, TemplateRef } from '@angular/core';
export interface RowContext<T> {
$implicit: T;
index: number;
}
@Component({
selector: 'app-list',
imports: [NgTemplateOutlet],
template: `
<ul>
@for (item of items(); track $index) {
<li>
<ng-container
[ngTemplateOutlet]="row()"
[ngTemplateOutletContext]="{ $implicit: item }"
/>
</li>
}
</ul>
`,
})
export class List<T> {
readonly items = input.required<T[]>();
readonly row = input.required<TemplateRef<RowContext<T>>>();
}
✘ [ERROR] TS2741: Property 'index' is missing in type '{ $implicit: T; }' but required in type 'RowContext<T>'. [plugin angular-compiler]
- TS2741 is TypeScript’s code for “this object is missing a property its type requires”.
'{ $implicit: T; }'is the context the list passes.RowContext<T>is the type therowinput promised. The promise has anindex, and the object doesn’t.
The error is in list.ts, not in the parent, and the parent didn’t even use index. The list promised every parent an index, so it has to give one. Either put index: $index back, or take index out of RowContext if no row should rely on it. Here we put it back:
// src/app/list.ts
import { NgTemplateOutlet } from '@angular/common';
import { Component, input, TemplateRef } from '@angular/core';
export interface RowContext<T> {
$implicit: T;
index: number;
}
@Component({
selector: 'app-list',
imports: [NgTemplateOutlet],
template: `
<ul>
@for (item of items(); track $index) {
<li>
<ng-container
[ngTemplateOutlet]="row()"
[ngTemplateOutletContext]="{ $implicit: item, index: $index }"
/>
</li>
}
</ul>
`,
})
export class List<T> {
readonly items = input.required<T[]>();
readonly row = input.required<TemplateRef<RowContext<T>>>();
}
The page shows:
Ana
Ben
In older code
Content projection has hardly changed in years. <ng-content>, select, ngProjectAs, <ng-template> and ngTemplateOutlet all look the same in older projects. Fallback content inside <ng-content> is the newest piece; older code got the same effect with extra logic in the child.
You’ll often see the outlet written with a star: <ng-container *ngTemplateOutlet="row; context: { $implicit: item }" />. That’s short for the two bindings we used. Older code also used <ng-container> and <ng-template> a lot with structural directives like *ngIf and *ngFor, for example <ng-container *ngIf="user"> to show a group of elements without a wrapper. The @if and @for blocks from Part 4 replace those, and need no <ng-container>. One difference with the star form: if you forget to import NgTemplateOutlet, the build only prints a warning that starts NG8116: A structural directive `ngTemplateOutlet` was used in the template without a corresponding import in the component., and the spot on the page stays empty. We tried it. Read every ▲ [WARNING] line.
Best practices
- Use
<ng-content />when the parent supplies markup, and an input when it supplies data. A title string is an input. A body with a button is content. It replaces passing HTML strings into inputs, which loses bindings and type checks. - Mark slots with attribute selectors like
[card-title]. The parent can then use any element for the slot, and the attribute doesn’t change how it looks. It replaces matching onh2or a class that the parent might also use for styling. - Always give a multi-slot component a default slot, unless dropping content is what you want. Otherwise anything that matches nothing disappears without a word.
- Use a template input when content should be created late, or once per item.
input.required<TemplateRef<...>>()plusngTemplateOutletreplaces<ng-content>inside@ifor@for. - Type the context with an interface, and put the main value in
$implicit.TemplateRef<RowContext<T>>makes the child keep its promise. It replacesTemplateRef<any>, which checks nothing. - Import
NgTemplateOutlet, notCommonModule. Yourimportsthen say exactly what the template uses.
Tips and traps
- Content that vanishes. Nothing between your tags shows up, with no error, though a component in it is still created. The child has no
<ng-content />, or no default slot for content that matched noselect. Add the slot. - A wrapper that breaks a match. You wrap a title in a
<div>, and it jumps to the default slot.selectonly matches elements directly inside the component tag. Remove the wrapper, or use<ng-container ngProjectAs="...">. <ng-content>inside@if. A component in the content is created at page load, even while hidden, and keeps its state when hidden. Pass a template instead, as the panel does.<ng-content>inside@for. You hope to repeat the content once per item. It shows up once, in the last item only; we tried it. Use a row template.- NG8002 on
ngTemplateOutlet.Can't bind to 'ngTemplateOutlet' since it isn't a known property of 'ng-container'. ImportNgTemplateOutletfrom@angular/common. - A typo in the parent’s row template.
let-variables have the typeany, so{{ book.titel }}builds and shows nothing. Look at the rendered rows. - Styling projected content from the child. The child’s CSS rules don’t reach the parent’s elements, though inherited properties like
colorstill flow in from the child’s wrappers. Style the content in the parent, or style the child’s own wrapper elements around the slots. Part 7 covers the details.
The parent decides what goes in, the child decides where it goes, and an
<ng-template>decides when it’s made.
Exercises
Exercise 1. This dialog should show a heading, a message and a button. The message is missing, and there’s no error. Why? Fix it in dialog.ts.
// src/app/dialog.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-dialog',
template: `
<div role="dialog">
<ng-content select="h2" />
<ng-content select=".buttons" />
</div>
`,
})
export class Dialog {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Dialog } from './dialog';
@Component({
selector: 'app-root',
imports: [Dialog],
template: `
<app-dialog>
<h2>Delete file?</h2>
<p>This can't be undone.</p>
<div class="buttons"><button>Delete</button></div>
</app-dialog>
`,
})
export class App {}
Delete file?
Delete
Exercise 2. Write an Alert component in src/app/alert.ts. It has a title slot for elements with the alert-title attribute, with the fallback text Notice, and a default slot for the message. In App, use it twice: once with the title Saved and the message Your changes are safe., and once with only the message Check your email.. The page should show Saved, Your changes are safe., Notice and Check your email., in that order.
Exercise 3. Change the List from the row-template example so each row can also read how many items there are. A parent should be able to show rows like 1 of 2: Dune. Hint: @for gives you $count.
Answers
1. The paragraph matches neither select, and the dialog has no default slot, so the paragraph is never put on the page. Add a plain <ng-content /> where the message should go:
// src/app/dialog.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-dialog',
template: `
<div role="dialog">
<ng-content select="h2" />
<ng-content />
<ng-content select=".buttons" />
</div>
`,
})
export class Dialog {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Dialog } from './dialog';
@Component({
selector: 'app-root',
imports: [Dialog],
template: `
<app-dialog>
<h2>Delete file?</h2>
<p>This can't be undone.</p>
<div class="buttons"><button>Delete</button></div>
</app-dialog>
`,
})
export class App {}
The page shows:
Delete file?
This can't be undone.
Delete
2. Two slots, one with fallback content:
// src/app/alert.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-alert',
template: `
<div role="status">
<strong><ng-content select="[alert-title]">Notice</ng-content></strong>
<p><ng-content /></p>
</div>
`,
})
export class Alert {}
// src/app/app.ts
import { Component } from '@angular/core';
import { Alert } from './alert';
@Component({
selector: 'app-root',
imports: [Alert],
template: `
<app-alert>
<span alert-title>Saved</span>
Your changes are safe.
</app-alert>
<app-alert>Check your email.</app-alert>
`,
})
export class App {}
The page shows:
Saved
Your changes are safe.
Notice
Check your email.
Plain text with no element around it, like Your changes are safe., matches no select, so it goes to the default slot.
3. Add count to the context type, pass $count in the context, and read it in the parent with let-count="count":
// src/app/list.ts
import { NgTemplateOutlet } from '@angular/common';
import { Component, input, TemplateRef } from '@angular/core';
export interface RowContext<T> {
$implicit: T;
index: number;
count: number;
}
@Component({
selector: 'app-list',
imports: [NgTemplateOutlet],
template: `
<ul>
@for (item of items(); track $index) {
<li>
<ng-container
[ngTemplateOutlet]="row()"
[ngTemplateOutletContext]="{ $implicit: item, index: $index, count: $count }"
/>
</li>
}
</ul>
`,
})
export class List<T> {
readonly items = input.required<T[]>();
readonly row = input.required<TemplateRef<RowContext<T>>>();
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { List } from './list';
@Component({
selector: 'app-root',
imports: [List],
template: `
<app-list [items]="titles()" [row]="titleRow" />
<ng-template #titleRow let-title let-i="index" let-count="count">
{{ i + 1 }} of {{ count }}: {{ title }}
</ng-template>
`,
})
export class App {
protected readonly titles = signal(['Dune', 'Emma']);
}
The page shows:
1 of 2: Dune
2 of 2: Emma
Because count is in RowContext, forgetting count: $count in the list is now a TS2741 build error, like the one in the worked example.
What’s next
The panel and the list got their templates as inputs. In Part 10, we’ll use viewChild and contentChild to find elements, components and templates from inside a component, and follow a component’s life from creation to destroy.