Angular 2+: Get child element of @ViewChild()

馋奶兔 提交于 2019-12-10 14:28:36

问题


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.


回答1:


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.




回答2:


use ViewChildren instead which gets all elements with same tag.

@ViewChildren('parent') parents: QueryList<any>;

To convert those elements to array:

const arr = this.parent.toArray();

Choose first element:

const el = arr[0]

Access child html of first element: const innerHtml = el.nativeElement.innerHtml;




回答3:


In your case, when you need only one and first child.

this.parent.nativeElement.firstChild



来源:https://stackoverflow.com/questions/51828448/angular-2-get-child-element-of-viewchild

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!