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

前端 未结 4 1131
[愿得一人]
[愿得一人] 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<HTMLElement>;
    
    public getChildren() {
      const parentElement = this.parentRef.nativeElement;
      const firstChild = parentElement.children[0];
      const firstImage = parentElement.querySelector("img");
      ...
    }
    

    See this stackblitz for a demo.

    0 讨论(0)
  • 2021-01-17 19:44

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

    this.parent.nativeElement.firstChild

    0 讨论(0)
  • 2021-01-17 19:48

    HTML

    <div #parent>
      <span id="child">
    </div>
    

    TS

     @ViewChild('parent',{static:false}) parentDiv:ElementRef
     this.parentDiv.nativeElement.firstChild
    

    You can check this out if you want do any operations in it renderer2

    0 讨论(0)
  • 2021-01-17 19:53

    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;

    0 讨论(0)
提交回复
热议问题