ng-content 選擇性投影

1. 基本投影

最簡單的使用方式:

// my-card.component.ts
@Component({
  template: `
    <div class="card">
      <ng-content></ng-content>
    </div>
  `
})

使用時:

<my-card>
  這裡的內容會被投影到 ng-content 的位置
</my-card>

2. 選擇性投影

可以指定不同內容的投影位置:

// fancy-button.component.ts
@Component({
  template: `
    <span>
      <ng-content />
    </span>
    <span class="icon">
      <ng-content select="icon"> → </ng-content>
    </span>
  `
})

使用時有兩種方式:

<!-- 方式一:使用默認箭頭 -->
<button appButton>
  Submit
</button>

<!-- 方式二:自定義圖標 -->
<button appButton>
  Submit
  <span ngProjectAs="icon">⌲</span>
</button>

重要說明

  1. <ng-content /> 不帶 select 時會捕獲所有未被其他 ng-content 捕獲的內容

  2. ngProjectAs 可以讓任何元素被當作指定的選擇器來處理

  3. <ng-content select="icon">→</ng-content> 中,箭頭(→)是固定內容,不是投影內容

實用技巧

使用 ngProjectAs 自定義各種圖標:

<button appButton>
  Delete
  <span ngProjectAs="icon">🗑️</span>
</button>

<button appButton>
  Settings
  <span ngProjectAs="icon">⚙️</span>
</button>

這樣的設計讓按鈕元件既能保持一致性(都有圖標),又能根據需要靈活變化。

Last updated