Sub topic 1
Why components need to accept content
Prerequisites
Assume you know basic Angular components, templates, TypeScript, component selectors, and CSS selectors. Content projection is Angular’s way to let a parent provide markup that a child component renders inside its own template.
A component that owns all its markup is difficult to reuse. A card may always need a heading, body, and actions, but different parents should supply different text and controls. The child defines the layout. The parent supplies the content.
Your first `ng-content` slot
ng-content is a projection slot. Angular places the content between a component’s opening and closing tags into that slot.
import { Component } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<article class="card">
<ng-content></ng-content>
</article>
`,
})
export class CardComponent {}A parent can now reuse the layout with different content:
<app-card>
<h2>Account settings</h2>
<p>Change your notification preferences.</p>
</app-card>The parent creates and owns the projected elements. The child controls where Angular displays them. This separation lets the child provide consistent structure and styling without knowing the exact content.
Named slots with `select`
A component can define several slots. The select attribute accepts a CSS selector and routes matching projected elements to that slot.
import { Component } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<header><ng-content select="[panel-title]"></ng-content></header>
<section><ng-content></ng-content></section>
<footer><ng-content select="[panel-actions]"></ng-content></footer>
`,
})
export class PanelComponent {}The parent marks content for each destination:
<app-panel>
<h2 panel-title>Settings</h2>
<p>This paragraph uses the default slot.</p>
<button panel-actions>Save</button>
</app-panel>The attribute selectors match the heading and button. Content that matches no named selector goes to the plain slot. Define named slots when placement matters, and keep a default slot for ordinary body content.
Exercise
Which slot receives <button panel-actions>Save</button> in the example?
Show answer
The slot with select="[panel-actions]", because the button has the panel-actions attribute.