How to Find Children Element in @ViewChild Angular

2020-03-02 06:59发布

问题:

import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div #container>
        <p>para 1</p>
        <p>para 2</p>
        <button>button 1</button>
    </div>
  `
})
export class AppComponent {
  @ViewChild('container') myDiv;

  ngAfterViewInit(){
    //this console.log would print this [p, p, button]
    console.log(this.myDiv.nativeElement.children);
    //how can I access to only p nativeElement only? 
  } 

}

See plunker

回答1:

You can try the following to get array of p elements:

Array.from(this.myDiv.nativeElement.children).filter(tag => tag.tagName === 'P')


标签: angular