ng-container
功能
ng-container是Angular中的一个元素,它可以作为结构指令的宿主。它可以让我们使用结构指令而不需要额外的元素,这样可以略微提高性能并保持DOM和样式的清晰。
特性
ng-container并不创建与它相对应的页面元素,如下面的代码
<ng-container>
<div>
哈哈哈
</div>
</ng-container>
最终在页面上只有作为ng-container子元素的div被创建出来,并没有ng-container对应的页面元素。此外也可以看出ng-container/ng-template不会影响其子元素的创建和渲染。
使用及优势
使用结构指令的时候,一般有两种方法,一种是直接在标签中加上指令,但是一般不推荐这么使用,因为标签中可能还含其他一些属性,把结构指令和这些属性混杂在一起,会使代码看着不是很清晰,所以一般会用一个div标签包裹一下
<div *ngIf="show">
<table class="table table-noborder" align="left" border="12px" >
<thead>
<tr>
<th>文件名</th>
<th>分类</th>
<th>上传时间</th>
</tr>
</thead>
<tbody>
<tr>
<td>fileName</td>
<td>fileCategory</td>
<td>uploadTime</td>
</tr>
</tbody>
</table>
</div>
问题来了,当出于上述意图而存在的这种div元素较多时,页面的dom结构就会显得臃肿,这种情况下使用ng-container来作为结构指令的宿主自然是一个更好的选择,因为其不会生成额外的页面元素。因此上述代码可以改成
<ng-container *ngIf="show">
<table class="table table-noborder" align="left" border="12px" >
<thead>
<tr>
<th>文件名</th>
<th>分类</th>
<th>上传时间</th>
</tr>
</thead>
<tbody>
<tr>
<td>fileName</td>
<td>fileCategory</td>
<td>uploadTime</td>
</tr>
</tbody>
</table>
</ng-container>
ng-template
功能 提供一个所谓模板,可以在其他地方使用并最终展示模板的内容。
特性 和ng-container不同,默认情况下ng-template包裹的内容是不会展示在页面中的,如下面的代码
<ng-template *ngIf="true">
<p>This is a paragraph.</p>
</ng-template>
最终将不会在页面上渲染任何元素。
使用及优势
经典的使用方法如下所示:
<ng-template #myTemplate let-name let-age="age">
<p>Hello {{name}}, you are {{age}} years old.</p>
</ng-template>
<ng-container [ngTemplateOutlet]="myTemplate" [ngTemplateOutletContext]="{name: 'Alice', age: 20}"></ng-container>
效果图:
let-xx语法定义了一个变量,使用模板时可以通过ngTemplateOutletContext将变量的值传过去。
特别的,如果只有一个变量,那么使用Context传值时,不用指定具体的变量名,使用$implicit代替即可。
<ng-template #myTemplate let-name let-age="age">
<p>Hello {{name}}</p>
</ng-template>
<ng-container [ngTemplateOutlet]="myTemplate" [ngTemplateOutletContext]="{$implicit: 'Alice'}"></ng-container>
效果图: