ng6的ng-template的一个用法

组件模板:

<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是要传递什么进去

转载于:https://my.oschina.net/u/1540190/blog/1840309

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值