解释
其实和html5的template是一样的就是将模板保存到html中然后需要时再抓出来显示到指定位置
代码
import { Component, ViewChild, TemplateRef,ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-root',
// templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
template: `
<div>
<ng-template #tpl>
<span>鬼子到我想干什么</span>
</ng-template>
<div #container></div>
<button (click)="showTpl()">btn</button>
</div>
`
})
export class AppComponent {
title = 'try-tpl';
@ViewChild('tpl') tt: TemplateRef<void>;
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
showTpl() {
this.container.createEmbeddedView(this.tt);
}
}
当然其实也可以
import { Component, ViewChild, TemplateRef,ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-root',
// templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
template: `
<div>
<ng-template #tpl>
<span>鬼子到我想干什么</span>
</ng-template>
<div #container></div>
<button (click)="showTpl()">btn</button>
</div>
`
})
export class AppComponent {
title = 'try-tpl';
@ViewChild('tpl') tt: TemplateRef<void>;
@ViewChild('tpl', { read: ViewContainerRef }) container: ViewContainerRef;
showTpl() {
this.container.createEmbeddedView(this.tt);
}
}
效果是一样的
viewContainerRef 获取到的就是一个容器
拓展
ngFor和ngIf其实就是用的,没有这个标签的原因是*这语法糖
<div *ngFor="let hero of heroes;">
{{hero.name}}
</div>
解析成
<ng-template ngFor let-hero [ngForOf]="heroes" >
<div>{{hero.name}}</div>
</ng-template>