【发布时间】:2021-11-21 12:05:49
【问题描述】:
我想在该组件中引用该组件的子元素。 我已经使用 ViewChild、ViewChildren、ContentChild、ContentChildren 尝试了 ElementRef、TemplateRef 和 QueryList,但没有运气。
<app-modal>
<section #reference>
<h1>I NEED THIS ELEMENT</h1>
</section>
</app-modal>
我想要完整引用 section 元素及其子元素作为 html 元素。
@ViewChild('reference') ref: ElementRef;
ngAfterViewInit(): void {
console.log(this.ref.nativeElement); -----> logged TypeError: Cannot read properties of undefined (reading 'nativeElement')
}
ngAfterContentInit(){
console.log(this.ref.nativeElement); -----> logged TypeError: Cannot read properties of undefined (reading 'nativeElement')
}
这样我就可以将相同的 ref 发送到另一个组件并在 dev 中显示为 innerHTML。
<div innerHTML='ref'></div>
我们非常感谢您的快速帮助。
【问题讨论】:
-
打错字了,我更正了。我收到了
TypeError: Cannot read properties of undefined (reading 'nativeElement') -
请在此处查看完整代码...dev.to/rammurthykota/…
-
你确定这不是因为“文本”中的拼写错误...
-
你检查编译错误了吗。
-
尝试
ViewChild('reference', {static: true}) ref: ElementRef;并在ngOnInit方法中访问ref属性
标签: javascript angular typescript