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

前端 未结 4 1130
[愿得一人]
[愿得一人] 2021-01-17 19:04

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

In template.htm

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 19:39

    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;
    
    public getChildren() {
      const parentElement = this.parentRef.nativeElement;
      const firstChild = parentElement.children[0];
      const firstImage = parentElement.querySelector("img");
      ...
    }
    

    See this stackblitz for a demo.

提交回复
热议问题