在angular中,有這樣三個自帶的標簽,但是在angular的文檔中沒有說明,只有在api中有簡單的描述,摸索了半天才搞懂是咋回事。
ng-content
<div> <ng-content select=".header"> </ng-content> <hr/> <ng-content select=".footer"> </ng-content> </div>
ng-content有一個select的屬性,可以選擇對應的嵌入標簽的屬性,.header的意思就是選中class=header的標簽填充到當前的位置
<app-contentdemo> <div class="header"> header </div> <div class="footer"> footer </div> </app-contentdemo>
一般的布局類的組件,都是使用ng-content實現,比如ng-zorror的layout組件,都可以使用ng-content實現
ng-container
ng-container在界面上是沒有任何意義的,在瀏覽器的審查元素中,無法看到它,container意思就是容器。只裝東西,不會顯示。
<ng-container> <h1>test</h1> </ng-container>
ng-template
template是模板的意思,ng-template標簽主要就是用來加載一個模板。
<ng-template> <h2>模板</h2> </ng-template>
但是如果是這樣,在瀏覽器中是不會渲染。必須要使用[ngif]=ture或者ngTemplateOutlet才能讓模板內容渲染出來
使用[ngif]=true
<ng-template [ngIf]="true" ]> <h2>模板</h2> </ng-template>
使用ngTemplateOutlet
<ng-container *ngTemplateOutlet="greet"></ng-container> <ng-template #greet><span>Hello</span></ng-template>
組件嵌套中的模板上下文
使用primeng的時候,表格組件中,會出現嵌套的ng-template,並能獲取到上下文中的對象。這種是怎么做的呢?
在ngTemplateOutlet可以傳遞一個上下文,直接把對象傳遞進去的就好了
<table style="width: 100%"> <thead> <tr> <th *ngFor="let label of labellist">{{label}}</th> </tr> </thead> <tbody> <ng-container *ngFor="let item of data;let i = index"> <tr> <ng-container *ngFor="let row of tableColumn"> <td style="" align="center"> <ng-container *ngIf="row.prop"> <label>+</label> {{item[row.prop]}} </ng-container> <ng-container *ngIf="row.scope"> <ng-container *ngTemplateOutlet="row.scope;context:{row:item}"></ng-container> </ng-container> </td> </ng-container> </tr> </ng-container> </tbody> </table>
使用
<app-apptable [data]="data"> <app-app-col label="用戶名" prop="username"></app-app-col> <app-app-col label="密碼" prop="pwd"></app-app-col> <app-app-col label="昵稱" prop="pwd"></app-app-col> <app-app-col label="測試" scope="scope"> <ng-template #scope let-data="row"> <span style="color: red">00-{{data.username}}</span> </ng-template> </app-app-col> </app-apptable>
在ng-teamplate中 #scope是當前的模板的名字引用,let-xxxx是定義當前的作用域內的用於接受上下文對象的屬性,
然后在在模板的作用域類,就可以使用let-xxx的xxx去點出ngTemplateOutlet的context傳遞的對象。
以上差不多就是我對着三個標簽的理解