前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ng6的ng-template的一个用法 原

ng6的ng-template的一个用法 原

作者头像
申君健
发布2018-09-21 09:51:33
1.6K0
发布2018-09-21 09:51:33
举报
文章被收录于专栏:前端侠2.0前端侠2.0前端侠2.0

组件模板:

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档