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?
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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With