首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >访问模板元素中的模板引用

访问模板元素中的模板引用
EN

Stack Overflow用户
提问于 2017-03-01 14:37:50
回答 2查看 5.8K关注 0票数 10

我正在使用一个库,它希望我将指令的主体指定为template元素的子元素

代码语言:javascript
运行
复制
<template customDirective>
   <custom-element #lookup></custom-element>
</template>

是否有一种方法可以访问我的组件中的custom-element#lookup

比如,

代码语言:javascript
运行
复制
@Component({
  selector: 'app-test',
  template: `
    <template customDirective>
       <custom-element #lookup></custom-element>
    </template>
  `
})
export class TestComponent {
  @ViewChild('lookup') viewChildRef;
  @ContentChild('lookup') contentChildRef;

  constructor() {
  }

  ngAfterContentInit(): void {
     console.log(this.viewChildRef); // <-- undefined
     console.log(this.contentChildRef); // <-- undefined
  }
}

在这两种情况下,我都得到了undefined

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-01 19:42:52

除非您不创建嵌入式视图,否则无法获得对模板中组件的引用。

尝试使用setter,例如:

代码语言:javascript
运行
复制
@ViewChild('lookup') 
set lookUp(ref: any) {
  console.log(ref);
}

柱塞实例

票数 9
EN

Stack Overflow用户

发布于 2017-03-01 15:01:32

尝试查看lookedUpCustomElemRef内部的ngAfterViewInit回调。

https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42534524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档