Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find Children Element in @ViewChild Angular2?

Tags:

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

}

See plunker

like image 874
Vicheanak Avatar asked Jul 01 '16 15:07

Vicheanak


People also ask

How do you use View for kids?

Descriptionlink. Use to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value. View queries are set before the ngAfterViewInit callback is called.


1 Answers

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

Array.from(this.myDiv.nativeElement.children).filter(tag => tag.tagName === 'P')
like image 151
yurzui Avatar answered Dec 08 '22 12:12

yurzui