如何在Angular中引用组件的子元素



我希望在该组件中引用该组件的子元素。我用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>

非常感谢您的快速帮助。

可能您可以使用:

<div [innerHTML]="ref.outerHTML"></div>

然而,更常见的方法是(假设您想在app-modal中使用HTML(:

<app-modal>
<section name="reference">

然后将其注入到应用程序模式的模板中:

<ng-content select="section[name=reference]"></ng-content>

最新更新