NGコンテンツを用いた角度におけるコンテンツ投影


ために再利用可能で柔軟なコンポーネントのコンテンツプロジェクションを作成する角度で大きなオプションです.NGコンテンツを使用すると、角度でコンテンツの投影を行うことができます.
一般的なコンテンツプロジェクションでは、あるコンポーネントから別のコンポーネントにコンテンツを挿入または投影することを意味します.たとえば、親コンポーネント内で使用するコンポーネント(子コンポーネント)に動的なHTML要素を挿入します.
角度でのコンテンツ投影の一般的な実装
  • シングルスロット内容投影
  • マルチスロット内容投影
  • 条件付コンテンツプロジェクション
  • シングルスロットコンテンツプロジェクション


    単一のスロットコンテンツの投影は、コンポーネントにプロジェクトを必要とするコンテンツの単一のソースがあることを意味します.例を理解しましょう.

    child-component.html (selector: cp-child)


    <h2>Single Slot Content Projection Example</h2>
    <ng-content></ng-content>
    <input type="text" />
    <p>This is simple example to demonstrate the single slot content projection.</p>
    

    parent-component.html


    <cp-single>
      <mat-icon>email</mat-icon>
    </cp-single>
    <cp-single>
      <mat-icon>home</mat-icon>
    </cp-single>
    
    ここでは、同じコンポーネントが異なる内容を投影することによって再利用されるのを見ることができます

    マルチスロットコンテンツプロジェクション


    複数のコンテンツを同じコンポーネントに投影する必要がある場合は、NGコンテンツのselect属性を使用してマルチスロットプロジェクションでそれを達成することができます.の例を見てみましょう.

    child-component.html (selector: cp-child)


    <h2>Multi Slot Content Projection Example</h2>
    <ng-content select="[projected-label]"></ng-content>
    <ng-content select="[projected-icon]"></ng-content>
    <input matInput />
    <ng-content select="[projected-hint-msg]"></ng-content>
    <p>This is simple example to demonstrate the multi slot content projection.</p>
    

    parent-component.html


    <cp-multi-slot>
      <mat-icon projected-icon>email</mat-icon>
      <mat-label projected-label>Enter Email</mat-label>
      <mat-hint projected-hint-msg>[email protected]</mat-hint>
    </cp-multi-slot>
    
    ここで、各NGコンテンツには、親コンポーネントからプロジェクションされたコンテンツと一致する名前を持つselect属性があります.
    SELECT属性に言及しないならば、そのマッチしない内容はそのプレースホルダに投影されるでしょう.
    これはマルチスロットプロジェクションがどのように見えるかです.

    条件付きコンテンツプロジェクション


    我々は一定の条件に基づいてコンテンツをプロジェクト化する必要がある状況があるとしましょう.
    しかし、そのようなシナリオではNGコンテンツよりNGテンプレートを使うことを推奨します.その理由は、コンテンツがレンダリングされていなくても常に反映されますが、NGテンプレートはコンテンツがレンダリングされたときにのみ生成されます.

    NGProjectas :


    別の要素の一部である特定のコンテンツをプロジェクトにしたい場合には、NGコンテナ内のコンテンツなどを参照してください.例を見てみましょう

    parent-component.html


    <cp-multi-slot>
      <ng-container ngProjectAs="complex-ele">
        <h2>This the Demo of Complex content projection</h2>
        <p>Simple Demo of complex content projection using ngProjectAs</p>
      </ng-container>
      <div another-ele>
        <p>This is another element to project into component</p>
      </div>
    </cp-multi-slot>
    

    component where the dynamic content projected


    <p>Complex Multi-slot Projection</p>
    <ng-content select="['complex-ele']"></ng-content>
    <ng-content select="['another-ele']"></ng-content>