Angular 2+:获取@ViewChild()的子元素

btx*_*btx 5 viewchild angular-components angular

如何访问子元素(此处<img>)的@ViewChild()在角2+没有明确的声明?

在template.html中

<div #parent>
  <!-- There can be anything than <img> -->
  <img src="http://localhost/123.jpg" alt="">
</div>
Run Code Online (Sandbox Code Playgroud)

在component.ts中

@ViewChild('parent') parent;

public getFirstChild() {
   this.firstChild = this.parent.? //
}
Run Code Online (Sandbox Code Playgroud)

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

<div #parent>
    <ng-content></ng-content>
</div>
Run Code Online (Sandbox Code Playgroud)

因此,#parent无需显式声明即可访问需要的子元素。

Con*_*Fan 7

您可以使用by 的nativeElement属性来获取相应的HTML元素。从那里,标准的DOM方法和属性可以访问其子级:ElementRefViewChild

  • element.children
  • element.querySelector
  • 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");
  ...
}
Run Code Online (Sandbox Code Playgroud)

有关演示,请参见此堆叠闪电战。