gpt4 book ai didi

Angular 2+ : Get child element of @ViewChild()

转载 作者:太空狗 更新时间:2023-10-29 17:47:43 26 4
gpt4 key购买 nike

如何访问 <img> 的子元素(此处:@ViewChild())在 Angular 2+ 中没有显式声明?

在 template.html 中

<div #parent>
<!-- There can be anything than <img> -->
<img src="http://localhost/123.jpg" alt="">
</div>

在 component.ts 中

@ViewChild('parent') parent;

public getFirstChild() {
this.firstChild = this.parent.? //
}

目标是能够创建一个使用以下内容的通用组件:

<div #parent>
<ng-content></ng-content>
</div>

所以#parent的子元素无需明确声明即可访问。

最佳答案

可以使用ViewChild给出的ElementRefnativeElement属性来获取对应的HTML元素。从那里,标准的 DOM 方法和属性可以访问它的 child :

  • 元素.children
  • 元素查询选择器
  • element.querySelectorAll
  • 等等

例如:

@ViewChild("parent") private parentRef: ElementRef<HTMLElement>;

public getChildren() {
const parentElement = this.parentRef.nativeElement;
const firstChild = parentElement.children[0];
const firstImage = parentElement.querySelector("img");
...
}

参见 this stackblitz用于演示。

关于 Angular 2+ : Get child element of @ViewChild(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51828448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com