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

前端之家收集整理的这篇文章主要介绍了如何在@ViewChild Angular2中查找子元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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

解决方法

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

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

猜你在找的Angularjs相关文章