Sub topic 3
Named slots with select
The previous chapter showed a single <ng-content /> slot that receives everything the parent places between the component's tags. This chapter covers components that need several slots. It assumes you can write a standalone component, know the CSS selector syntax for element names, attributes and classes, and have read the single-slot chapter.
Why one slot is not enough
A wrapper component often has a fixed layout with distinct regions. A dialog has a title bar, a body and a button row. A card has a header, a media area and a footer. With one <ng-content />, the parent's content would land in a single place, and the component could not tell a title from a body.
The select attribute on <ng-content> solves this. It takes a CSS selector. Each top-level node the parent places inside the component's tags is tested against the selectors of the component's slots, and the node is rendered in the slot whose selector it matches.
A panel with three slots
This component defines a title slot, a default slot and an actions slot:
import { Component } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<header><ng-content select='[panel-title]' /></header>
<section><ng-content /></section>
<footer><ng-content select='[panel-actions]' /></footer>
`,
})
export class PanelComponent {}The parent marks each element with an attribute that matches one of the selectors:
<app-panel>
<h2 panel-title>Settings</h2>
<p>This paragraph goes to the default slot.</p>
<button panel-actions>Save</button>
</app-panel>Angular renders this as:
<app-panel>
<header><h2 panel-title>Settings</h2></header>
<section><p>This paragraph goes to the default slot.</p></section>
<footer><button panel-actions>Save</button></footer>
</app-panel>Three details matter here.
- The order of the nodes in the parent does not affect the result. The order of the slots in the component template does. If the parent wrote the button first, it would still appear in the footer.
- The
panel-titleandpanel-actionsattributes are not directives or inputs. They are plain attributes that exist only so the selector can match them. Angular does not remove them from the output. - The
<ng-content>element itself is never rendered. Only the projected nodes appear in its place.
What a selector can match
The select value is a CSS selector, but Angular supports only the parts that can be checked against a single element's tag name, attributes and classes. The table shows the common forms.
| Selector | Matches |
|---|---|
| `select='h2'` | Any `<h2>` element |
| `select='[panel-title]'` | Any element with the attribute `panel-title` |
| `select='[slot=title]'` | Any element with `slot="title"` |
| `select='.actions'` | Any element with the class `actions` |
| `select='h2.lead'` | An `<h2>` that also has the class `lead` |
| `select='h2, h3'` | An `<h2>` or an `<h3>` (comma-separated list) |
| `select='app-icon'` | A component or element with that tag name |
| `select=':not(.hidden)'` | Elements that lack the class `hidden` |
Attribute selectors are the most common choice for a component library. They do not depend on the tag the consumer uses, so a consumer can mark a <h2>, a <div> or a custom component as the title. An element selector such as h2 is shorter, but it forces the consumer's markup choice. Component selectors such as app-icon work well when the slot should accept one kind of component only.
Here is a card that mixes several of these forms:
import { Component } from '@angular/core';
@Component({
selector: 'app-media-card',
template: `
<figure><ng-content select='img, video' /></figure>
<h3><ng-content select='h3, h4, .card-title' /></h3>
<div class='body'><ng-content /></div>
<p class='meta'><ng-content select='[meta]:not(.hidden)' /></p>
`,
})
export class MediaCardComponent {}The parent can then project an <img> or a <video> into the figure with no extra attributes at all.
Matching rules to remember
Only top-level nodes are matched
Angular tests the direct children of the component's tags. It does not look inside them. This is the most frequent cause of "my content is in the wrong place":
<app-panel>
<div class='header-wrapper'>
<h2 panel-title>Settings</h2>
</div>
</app-panel>The top-level node is the <div>. It has no panel-title attribute, so it goes to the default slot, and the <h2> inside it goes along with it. The title slot stays empty. To project the heading, remove the wrapper, or use ng-container with ngProjectAs, which a later chapter in this tutorial covers.
Matching is decided at compile time
Angular compares selectors with the element's tag name, its static attributes and its static classes when it compiles the parent's template. It does not re-evaluate the match at runtime. A class added later with classList.add() or a [class.actions]="flag" binding does not move the node to another slot. If the slot must change with state, use different markup in the parent, for example with @if and @else, or switch to ng-template, which is covered later in this tutorial.
First matching slot wins
A node goes into exactly one slot. If it matches more than one selector, Angular uses the first matching <ng-content> in the component's template order. A plain <ng-content /> with no select is different. It is a catch-all and takes only the nodes that no other slot claimed, wherever it sits in the template. The next chapter examines this default slot more closely.
import { Component } from '@angular/core';
@Component({
selector: 'app-overlap',
template: `
<ng-content select='.primary' />
<ng-content select='button' />
`,
})
export class OverlapComponent {}With <button class='primary'>OK</button> inside app-overlap, the button matches both selectors. It is rendered in the first slot, the .primary one.
Do not repeat a selector
Writing two <ng-content> elements with the same selector does not copy the content into both places. A projected node is created once and can sit in only one location. If you need the same content in two places, or only sometimes, take a template from the parent and render it with ngTemplateOutlet, as described in a later chapter.
Designing the slot contract
The selectors you choose form a public contract between your component and everyone who uses it. Changing panel-title to panel-heading later breaks every consumer silently, for the reason in the callout above. A few practices keep the contract manageable.
- Choose one naming convention for slot attributes and document it. Prefixing with the component name (
panel-title) avoids clashes with other attributes the consumer may use. - Keep the number of slots small. Three or four named slots are readable. Eight slots usually mean the component is doing the work of a layout and should be split.
- Decide for each slot whether it is optional. A missing slot leaves its wrapper element, such as the
<footer>above, in the DOM as an empty box. The fallback-content chapter shows how to supply default content for empty slots. Another option is to pick wrapper elements that collapse when empty. - Prefer attribute selectors when the consumer may use different tags, and component or element selectors when you want to restrict what a slot accepts.
Projection and the parent's context
Selecting is only about placement. The projected nodes still belong to the parent. The parent's template creates them, and the parent's bindings and component instance evaluate them. In the settings example, an expression in <h2 panel-title>{{ name }}</h2> reads name from the parent component, not from PanelComponent. The component cannot see these nodes' bindings, and it cannot reach into them from its own template. The chapter on ownership and the chapter on content queries cover this in detail.
Putting it together
This example builds a settings screen from the PanelComponent defined earlier. It shows named slots, the default slot, and parent-owned bindings in one place:
import { Component, signal } from '@angular/core';
import { PanelComponent } from './panel.component';
@Component({
selector: 'app-settings-page',
imports: [PanelComponent],
template: `
<app-panel>
<h2 panel-title>Settings for {{ user() }}</h2>
<p>Changes apply to every device.</p>
<p>Last saved: {{ saved() }}</p>
<button panel-actions (click)='save()'>Save</button>
<button panel-actions (click)='reset()'>Reset</button>
</app-panel>
`,
})
export class SettingsPageComponent {
user = signal('Ada');
saved = signal('never');
save() {
this.saved.set(new Date().toLocaleTimeString());
}
reset() {
this.saved.set('never');
}
}Both paragraphs go to the default slot, and both buttons go to the footer in the order they were written. The click handlers and the interpolations run against SettingsPageComponent. PanelComponent has no knowledge of save() or user.
Common mistakes
- Wrapping the marked element. Putting
panel-titleon an inner element while an outer<div>is the top-level node, as shown earlier. - Marking the wrong element. Putting
panel-actionson a wrapper<div>is fine, since the wrapper is the top-level node and moves as one unit. Putting it on the buttons inside that wrapper does nothing. - Expecting runtime reassignment. Toggling a class to change the slot has no effect after compilation.
- Relying on an element selector that the consumer might change. If the title selector is
h2, a consumer who needs an<h1>for accessibility cannot use the slot. An attribute selector avoids this.
Exercise
A component template contains <ng-content select='[slot-a]' /> followed by <ng-content />. A parent writes <app-x><div><span slot-a>One</span></div><span slot-a>Two</span></app-x>. Where do "One" and "Two" end up, and why?
Show answer
"Two" goes to the [slot-a] slot, because its <span> is a top-level node with the matching attribute. "One" goes to the default slot. Its <span> is nested inside a <div>, and Angular matches only top-level nodes. The <div> has no slot-a attribute, so the whole <div> is placed in the catch-all slot.
Exercise
Write the template of app-alert, a component with an icon slot that accepts only an <app-icon> component, a message slot that accepts anything else, and a dismiss-button slot selected by the attribute dismiss. Then write a parent usage that fills all three.
Show answer
Component template: <span class='icon'><ng-content select='app-icon' /></span> <div class='message'><ng-content /></div> <div class='dismiss'><ng-content select='[dismiss]' /></div>. Parent usage: <app-alert><app-icon name='warn' /><p>Disk almost full.</p><button dismiss>Close</button></app-alert>. The <app-icon> matches the element selector, the <button> matches the attribute selector, and the <p> matches nothing else, so it goes to the plain <ng-content />.