首页 > 解决方案 > Angular 2+:获取@ViewChild() 的子元素

问题描述

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

在模板.html

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

在组件.ts

@ViewChild('parent') parent;

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

目的是能够创建一个通用组件,该组件使用:

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

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

标签: angulartypescriptangular-componentsviewchild

解决方案


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

  • 元素.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");
  ...
}

请参阅此 stackblitz以获取演示。


推荐阅读