如果你嘗試在 Angular 中編寫可重復使用的組件,則可能會接觸到內容投射的概念。然后你發現了 <ng-content> ,并找到了一些關于它的文章,進而實現了所需的功能。
接下來我們來通過一個簡單的示例,一步步介紹 <ng-content> 所涉及的內容。
Simple example
在本文中我們使用一個示例,來演示不同的方式實現內容投影。由于許多問題與Angular 中的組件生命周期相關,因此我們的主要組件將顯示一個計數器,用于展示它已被實例化的次數:
import { Component } from '@angular/core';let instances = 0;@Component({ selector: 'counter', template: '<h1>{{this.id}}</h1>'})class Counter { id: number; constructor() { this.id = ++instances; }}上面示例中我們定義了 Counter 組件,組件類中的 id 屬性用于顯示本組件被實例化的次數。接著我們繼續定義一個 Wrapper 組件:
import { Component } from '@angular/core';@Component({ selector: 'wrapper', template: ` <div class="box"> <ng-content></ng-content> </div> `})class Wrapper {}現在我們來驗證一下效果:
<wrapper> <counter></counter> <counter></counter> <counter></counter></wrapper>
Targeted projection
有時你希望將包裝器的不同子項投影到模板的不同部分。為了處理這個問題, <ng-content> 支持一個 select 屬性,可以讓你在特定的地方投射具體的內容。該屬性支持 CSS 選擇器(my-element,.my-class,[my-attribute],...)來匹配你想要的內容。如果 ng-content 上沒有設置 select 屬性,它將接收全部內容,或接收不匹配任何其他 ng-content 元素的內容。長話短說:
import { Component } from '@angular/core';@Component({ selector: 'wrapper', template: ` <div class="box red"> <ng-content></ng-content> </div> <div class="box blue"> <ng-content select="counter"></ng-content> </div> `, styles: [` .red {background: red;} .blue {background: blue;} `]})export class Wrapper { }上面示例中,我們引入了 select 屬性,來選擇投射的內容:
<wrapper> <span>This is not a counter</span> <counter></counter></wrapper>
上述代碼成功運行后,counter 組件被正確投影到第二個藍色框中,而 span 元素最終會在全部紅色框中。請注意,目標 ng-content 會優先于 catch-all,即使它在模板中的位置靠后。
ngProjectAs
有時你的內部組件會被隱藏在另一個更大的組件中。有時你只需要將其包裝在額外的容器中即可應用
新聞熱點
疑難解答
圖片精選