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

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

问题描述

我正在使用一个库,希望我将指令的主体指定为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.

尝试使用以下设置器:

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

柱塞示例

Plunker Example

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

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