angular2+ ng-content淺談

        angular2+中的的內容映射使用的是ng-content指令,內容映射指的是在組件中嵌入模板代碼,方便定製可複用的組件。下面用例子來解釋一下ng-content的用法:

App.component.ts

<parent-content>
<child-content></child-content>
</parent-content>

可以把被包含的組件稱爲子組件,外層稱爲父組件。我們看下父組件怎麼寫的:
parent.component.ts

selector:'parent-content'
template:`<h1>this is parent-content </h1>
<ng-content></ng-content>`
再看下子組件是怎麼寫的:
child.component.ts
selector:'child-content',
template:'<p>this is child-content</p> '
這樣子組件child.component.ts的內容就會映射到parent.component.ts的“ng-content”中去,此時,如果我們想訪問或者操作子組件中的方法或屬性,可以通過下面的方式去訪問:
@ContentChildren(childComponent)child;(contentChildren和viewChildren還是有區別的,別搞混了)。
         另外:ng-content還有一個屬性,就是select,這裏的select有什麼用呢。主要作用是能夠選擇行的選擇要映射的組件,但是可供選擇的組件必須包含在父組件內部,這裏的選擇有三種選擇方式,分別是:屬性、標籤、CSS,下面咱們看下具體的使用方法:
1.屬性選擇

<ng-content select="[first]"></ng-content>
再看下父組件內部:

<parent-content>
<child-content first></child-content>
<child-content second></child-content>
</parent-content>
這裏選擇映射的就是具有first屬性的子組件 

2.標籤選擇

<ng-content select="child-content1"></ng-content>
再看下父組件內部:

<parent-content>
<child-content1></child-content1>
<child-content2></child-content2>
</parent-content>
這裏選擇映射的就是標籤名稱爲"child-content1"的子組件
3.CSS選擇

<ng-content select=".myChild"></ng-content>
再看下父組件內部:

<parent-content>
<child-content1 class="myChild"></child-content1>
<child-content2></child-content2>
</parent-content>

這裏選擇映射的就是類名爲"myChild"的子組件
這裏要說明一下,select的值不能設置成動態的,動態的值會導致無法正常映射組件.

說到這裏,不得不說一下一個屬性ngProjectAs,這個屬性是用來幹什麼的呢?我們來看一下:

我們將子組件包裝在<ng-container>這個容器中,並使用select屬性進行選擇映射,運行程序後看下結果:

parent.component.ts

<div style="border:1px solid red">
<ng-content></ng-content>
</div>
<div style="border:1px solid blue;margin-top:10px">
<ng-content select="child-content"></ng-content>
</div>
App.component.ts

<parent-content>
<ng-container>
<child-content></child-content>
</ng-container>
</parent-content>

此時我們發現,子組件只映射到了紅色的div中,藍色div中的子組件並沒有映射出來,這是因爲<ng-container>不在匹配select="child-content",這裏說下<ng-container>,這只是一個特殊的標籤,有點類似於template,Angular複用了HTML5規範中template 的tag的語義,不過並沒有真正利用其實現,因此在審查元素中是永遠也找不到一個template元素的。 不過,由於ng-container並不是HTML5中的,爲了保持區分度,採用了ng-作爲前綴。言歸正傳,要解決這個問題,就得利用ngProjectAs這個屬性,


<parent-content>
<ng-container ngProjectAs="child-content">
<child-content></child-content>
</ng-container>
</parent-content>

此時發現藍色div中映射了子組件。就解決了這個問題。









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章