访问模板元素内的模板引用 [英] Access template reference inside a template element

查看:31
本文介绍了访问模板元素内的模板引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的库希望我将指令的主体指定为 template 元素的子元素

I'm using a library that expects me to specify body of a directive as a child of template element

<template customDirective>
   <custom-element #lookup></custom-element>
</template>

有没有办法访问我的组件内的 custom-element#lookup.

Is there a way to access custom-element#lookup inside my component.

例如,

@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.

I'm getting undefined in both cases.

推荐答案

在不创建嵌入视图之前,您无法获得对模板内部组件的引用.

You cannot get reference to component inside template until you don't create embedded view.

尝试使用 setter,例如:

Try using setter like:

@ViewChild('lookup') 
set lookUp(ref: any) {
  console.log(ref);
}

Plunker 示例

这篇关于访问模板元素内的模板引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆