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.
In your case, when you need only one and first child.
use
ViewChildren
instead which gets all elements with same tag.To convert those elements to array:
Choose first element:
Access child html of first element: const innerHtml = el.nativeElement.innerHtml;
You can use the
nativeElement
property of theElementRef
given byViewChild
to get the corresponding HTML element. From there, standard DOM methods and properties give access to its children:For example:
See this stackblitz for a demo.