如何在@ViewChild Angular2中查找子元素? [英] How to Find Children Element in @ViewChild Angular2?

查看:164
本文介绍了如何在@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? 
  } 

}

请参见朋克车

推荐答案

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

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

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

这篇关于如何在@ViewChild Angular2中查找子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆