源代码:
<h1>ng-template</h1>
<br>
<!-- 通过ngIf结构型指令显示ng-template的内容 -->
<div class="lessons-list" *ngIf="!condition else elseTemplate">
<h3>标题:判断条件为真</h3>
</div>
<ng-template #elseTemplate>
<div>判断条件为假</div>
</ng-template>
<br>
运行时,准备渲染id为elseTemplate的模板:
TemplateRef有个方法:createEmbeddedView
兄弟comment节点:
TemplateRef对应ng-template的引用。
看一个实际的例子:
template 文件里,定义一个id为tpl的ng-template:
<ng-template #tpl>
<div>
Hello, ng-template!
</div>
</ng-template>
在宿主文件里:
import {AfterViewInit, Component, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
@Component({
selector: 'app-ng-template',
templateUrl: './ng-template.component.html'
})
export class NgTemplateComponent implements AfterViewInit {
condition = true;
@ViewChild('tpl')
tplRef: TemplateRef<any>;
myContext = {$implicit: '默认值', name: 'tuacy'};
constructor(private vcRef: ViewContainerRef) {
}
ngAfterViewInit(): void {
this.vcRef.createEmbeddedView(this.tplRef);
}
}
- 首先使用依赖注入,拿到ViewContainerRef引用。
- 使用@ViewChild, 拿到id为tpl的ng-template引用,类型为TemplateRef.
- 调用ViewContainerReference, 创建tpl模板实例。
注意,this.vcRef.createEmbeddedView, 虽然传入的是templateRef,但实际上正是调用templateRef的createEmbeddedView方法。
创建完view后立即渲染:
2021-4-20
Represents an embedded template that can be used to instantiate embedded views.
TemplateRef代表一个嵌入的模板,可以被用来实例化嵌入视图。
abstract class TemplateRef<C> {
abstract elementRef: ElementRef
abstract createEmbeddedView(context: C): EmbeddedViewRef<C>
}
elementRef:The anchor element in the parent view for this embedded view.
更多Jerry的原创文章,尽在:“汪子熙”: