Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child element

Please have a look at below code.

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

@Component ({
selector : 'other-component',
template : `
          <h2>OtherComponent<h2>
          <table #tab id="tab">
            <tr *ngFor="let val of valArray">
              <td>{{val}}</td>
              <input type="checkbox" [value]="val">
            </tr>
          </table>
         <button (click)="getChecked()">click me</button>`
})
export class OtherComponent{
  valArray = ['one','two','three','four'];
  @ViewChild ('tab') elem;
  getChecked = () => {

    console.log (this.elem.nativeElement.children[0].children)
  }

}

At the end of the table row there is checkbox which has been assigned row value (JSON object) now I want to collect all the checked boxes in angular 2.

In plain javascript I can do this easily like below

var yy = document.getElementById('tab').getElementsByTagName('input');

I got what I was looking for by this.elem.nativeElement.children[0].children

this gave me array of tr elements from which I got checked input boxes

Is there any better way to do this in angular 2?

like image 627
Nomad Avatar asked Sep 12 '16 19:09

Nomad


1 Answers

Change html (add #cbx to input) like:

<tr *ngFor="let val of valArray"><input #cbx type="checkbox" [value]="val"></tr>    

Then in your component class:

@ViewChildren('cbx') checkboxes;
getChecked = () => {
  console.log(this.checkboxes.toArray().map(x => x.nativeElement));
}

It will print array of desired checkboxes

See also live Plunker Example

Update

Alternative way is using dom api directly:

@ViewChild ('tab') elem;
getChecked = () => {
  console.log(this.elem.nativeElement.getElementsByTagName('input'));
  console.log(this.elem.nativeElement.querySelectorAll('input'));
}
like image 163
yurzui Avatar answered Oct 23 '22 00:10

yurzui