Content projection 让组件能够接收和渲染其父级传入的标记 — 通过 <ng-content> 放置。这是构建灵活、可复用的包装组件(卡片、对话框、布局)的方式,其中内部内容由使用者控制。(这是 Angular 对应的 Vue/web-component slots 和 React 的 children。)
Single-slot projection
ts
({
: ,
: ,
})
{}
<!-- parent: anything between the tags is projected into <ng-content> -->
<app-card>
<h2>Title</h2>
<p>Any content I want!</p>
</app-card>
该卡片提供样式化包装;父级决定内部放什么内容 — 比通过 @Input 传递字符串灵活得多。
@Component({
selector: "app-panel",
template: `
<header><ng-content select="[panel-header]"></ng-content></header>
<main><ng-content></ng-content></main> <!-- default slot -->
<footer><ng-content select="[panel-footer]"></ng-content></footer>
`,
})
export class PanelComponent {}
<app-panel>
<h1 panel-header>My Panel</h1> <!-- goes to the header slot -->
<p>Main body content</p> <!-- goes to the default slot -->
<button panel-footer>OK</button> <!-- goes to the footer slot -->
</app-panel>
select 属性(一个 CSS 选择器 — 属性、类或标签)将每部分投影内容路由到正确的 <ng-content> 插槽,支持多区域布局。
Projected content is created in the PARENT's context — its bindings, methods,
and lifecycle belong to the parent, not the wrapper component.
Content projection 是在 Angular 中构建可复用、可组合UI 组件的关键 — 卡片、模态框、标签、布局以及任何「壳」组件,其中使用者提供内部内容。
没有它,组件会很僵硬(只能通过 inputs 配置);有了 <ng-content>(以及用于多个插槽的 select),它们就变成了灵活的容器,这对设计系统和共享组件库至关重要。