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

查看:296
本文介绍了Angular 2+:获取@ViewChild()的子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在没有显式声明的情况下访问Angular 2+中@ViewChild()的子元素(在这里为<img>)?

How can I access the child elements (here: <img>) of @ViewChild() in Angular 2+ without explicit declaration?

在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.? //
}

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

The aim is, to be able to create a universal component that uses:

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

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

So the child elements of #parent need to be accessible without explicit declaration.

推荐答案

您可以使用ViewChild给出的ElementRefnativeElement属性来获取相应的HTML元素.从那里,标准的DOM方法和属性可以访问其子级:

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

例如:

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

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

有关演示,请参见> 此stackblitz .

See this stackblitz for a demo.

这篇关于Angular 2+:获取@ViewChild()的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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