Nomad Nomad - 1 year ago 350
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 : `
<table #tab id="tab">
<tr *ngFor="let val of valArray"><td>{{val}}</td><input type="checkbox" [value]="val"></tr>
<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 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 Source

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


Alternative way is using dom api directly:

@ViewChild ('tab') elem;
getChecked = () => {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download