我正在使用一个库,它希望我将指令的主体指定为template
元素的子元素
<template customDirective>
<custom-element #lookup></custom-element>
</template>
是否有一种方法可以访问我的组件中的custom-element#lookup
。
比如,
@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
。
发布于 2017-03-01 19:42:52
除非您不创建嵌入式视图,否则无法获得对模板中组件的引用。
尝试使用setter,例如:
@ViewChild('lookup')
set lookUp(ref: any) {
console.log(ref);
}
发布于 2017-03-01 15:01:32
尝试查看lookedUpCustomElemRef
内部的ngAfterViewInit
回调。
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
https://stackoverflow.com/questions/42534524
复制相似问题