コンテンツプロジェクションにより、コンポーネントは親から渡されたマークアップを受け入れてレンダリングでき、<ng-content>を通じて配置できます。これにより、柔軟で再利用可能なラッパーコンポーネント(カード、ダイアログ、レイアウト)を構築でき、その内部コンテンツはコンシューマーが制御できます。(Angular版のVue/ウェブコンポーネントスロットおよびReactのchildrenです。)
シングルスロットプロジェクション
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.
コンテンツプロジェクションは、Angular内で再利用可能で組み合わせ可能な UIコンポーネント(カード、モーダル、タブ、レイアウト、およびコンシューマーが内部コンテンツを提供する任意の「シェル」)を構築するための鍵です。
なければ、コンポーネントは硬い(入力でのみ設定可能)でしょう。<ng-content>(および複数スロット用のselect)があれば、柔軟なコンテナになり、これはデザインシステムと共有コンポーネントライブラリに不可欠です。