angular中ng-container與ng-template用法

ng-container與ng-template用法

1.ng-container與ng-template概念

ng-container既不是一個Component,也不是一個Directive,只是單純的一個特殊tag。
這點類似於template,Angular複用了HTML5規範中template 的tag的語義,不過並沒有真正利用其實現,因此在審查元素中是永遠也找不到一個template元素的。
不過,由於ng-container並不是HTML5中的,爲了保持區分度,採用了ng-作爲前綴。所以現在我們可以知道,ng-container是Angular所定義的一個特殊tag。

一般來說ng-container會與ng-template一起使用,ng-template 定義模板通過聲明引用變量#menuItems供ng-container調用,而ng-container使用menuItems來調用ng-template

<ng-template let-items="items" #menuItems>
  <ul class="tree">
    <ul *ngFor="let item of items">
      <li>
        <a [routerLink]="item.link">{{item.name}}</a>
        <ng-container *ngTemplateOutlet="menuItems; context: {items: item.children}"></ng-container>
      </li>
    </ul>
  </ul>
</ng-template>

<ng-container *ngTemplateOutlet="menuItems; context: {items: menuItems$ | async}"></ng-container>

2.ng-container遞歸調用ng-template標籤

通過ng-container 中的ngTemplateOutlet屬性的context字段來傳遞參數,ng-template中通過let-屬性名方式來接收參數。這類似調用函數時的形參。如果context中的形參爲空,則angular不會植入tag。遞歸調用的原理就是利用了參數爲空時,不植入多餘tag。這也是ng-container區別div標籤所在。

3.*ngTemplateOutlet

ngTemplateOutlet爲一指針,指向對應的模板進行輸出。


版權聲明:本文爲博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。 本文鏈接:https://www.cnblogs.com/JerryMouseLi/p/15798702.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章