Angular 2+:获取@ViewChild() 的子元素 [英] Angular 2+: Get child element of @ViewChild()
问题描述
如何在没有显式声明的情况下访问 Angular 2+ 中 @ViewChild()
的子元素(此处:)?
在 template.html 中
<!-- 除了 <img> 可以有任何东西--><img src="http://localhost/123.jpg" alt="">
在 component.ts
@ViewChild('parent') parent;公共 getFirstChild() {this.firstChild = this.parent.?//}
目标是能够创建一个通用组件,使用:
<ng-content></ng-content>
所以#parent
的子元素需要无需显式声明即可访问.
您可以使用 ViewChild
给出的 ElementRef
的 nativeElement
属性获取相应的 HTML 元素.从那里,标准 DOM 方法和属性可以访问其子项:
- element.children
- element.querySelector
- element.querySelectorAll
- 等
例如:
@ViewChild("parent") private parentRef: ElementRef;公共 getChildren() {const parentElement = this.parentRef.nativeElement;const firstChild = parentElement.children[0];const firstImage = parentElement.querySelector("img");...}
有关演示,请参阅此 stackblitz.
How can I access the child elements (here: <img>
) of @ViewChild()
in Angular 2+ without explicit declaration?
In template.html
<div #parent>
<!-- There can be anything than <img> -->
<img src="http://localhost/123.jpg" alt="">
</div>
In component.ts
@ViewChild('parent') parent;
public getFirstChild() {
this.firstChild = this.parent.? //
}
The aim is, to be able to create a universal component that uses:
<div #parent>
<ng-content></ng-content>
</div>
So the child elements of #parent
need to be accessible without explicit declaration.
You can use the nativeElement
property of the ElementRef
given by ViewChild
to get the corresponding HTML element. From there, standard DOM methods and properties give access to its children:
- element.children
- element.querySelector
- element.querySelectorAll
- etc.
For example:
@ViewChild("parent") private parentRef: ElementRef<HTMLElement>;
public getChildren() {
const parentElement = this.parentRef.nativeElement;
const firstChild = parentElement.children[0];
const firstImage = parentElement.querySelector("img");
...
}
See this stackblitz for a demo.
这篇关于Angular 2+:获取@ViewChild() 的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!