【问题标题】:How to have a reference of child elements of a component in Angular如何在Angular中引用组件的子元素
【发布时间】: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


【解决方案1】:

也许你可以使用:

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

但是,更常规的方式是(假设您想在 app-modal 中使用 HTML):

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

然后在app modal的模板中注入:

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

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 2017-05-25
    • 1970-01-01
    • 2020-09-30
    • 2019-12-11
    • 2017-01-08
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多