本文介绍了访问模板元素内的模板参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个库,希望我将指令的主体指定为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
更多推荐
访问模板元素内的模板参考
发布评论