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