Nomad Nomad - 2 months ago 51
TypeScript Question

get child element in angular 2

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

My question is, is there any better way to do this in angular 2.

Answer

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'));
}