如何在@ViewChild Angular2中查找子元素?

时间:2016-07-01 15:42:50

标签: angular

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? 
  } 

}

请参阅plunker

1 个答案:

答案 0 :(得分:6)

您可以尝试以下方法获取p元素数组:

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