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

btx picture btx · Aug 13, 2018 · Viewed 24.8k times · Source

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.

Answer

ConnorsFan picture ConnorsFan · Aug 13, 2018

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.