转载自 http://www.ngui.cc/news/show-131.html
在 Angular 中,我们可以通过 ViewChild 装饰器来获取视图中定义的模板元素,然后利用 ViewContainerRef 对象的 createEmbeddedView() 方法,创建内嵌视图。
import { Component, TemplateRef, ViewContainerRef, ViewChild,
AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<ng-template #tpl>
Hello, Semlinker!
</ng-template>
`,
})
export class AppComponent implements AfterViewInit{
@ViewChild('tpl')
tplRef: TemplateRef<any>;
constructor(private vcRef: ViewContainerRef) {}
ngAfterViewInit() {
this.vcRef.createEmbeddedView(this.tplRef);
}
}