Angular 2+:获取@ViewChild() 的子元素 [英] Angular 2+: Get child element of @ViewChild()

查看:46
本文介绍了Angular 2+:获取@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 给出的 ElementRefnativeElement 属性获取相应的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆