组件模板:
<ng-template #tpl>
<div>i am in tpl {{name }} </div>
</ng-template>
ts 组件内:
@ViewChild('tpl') tpl: TemplateRef<any>;
@ViewChild('tpl', {read: ViewContainerRef}) vc: ViewContainerRef; // tpl 和 vc同时绑定到一个元素上(竟然可以)
name = "123";
ngAfterViewInit() {
// 方法1 :通过tpl自己创建一个view,把view的第一个node插入到注释节点之前
const embeddedView = this.tpl.createEmbeddedView( null ); //模板的name显示不出, 传入this也不行
const p = this.tpl.elementRef.nativeElement.parentNode as HTMLElement;
p.insertBefore(embeddedView.rootNodes[0], this.tpl.elementRef.nativeElement);
// 方法2 : tpl 和 vc同时绑定到一个元素上(竟然可以)。 然后vc创建后tpl,直接插入到页面中
this.vc.createEmbeddedView(this.tpl);
}
以上两个方法都可以把tpl模板内容插入到组件中。
但第一种方法无法插入name的值。 参数是context,不明白它的context是要传递什么进去