Nom*_*mad 5 typescript angular
请看下面的代码.
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)
}
}
Run Code Online (Sandbox Code Playgroud)
在表格行的末尾有一个已分配行值(JSON对象)的复选框,现在我想收集角度2中的所有复选框.
在简单的JavaScript中,我可以像下面这样轻松地完成此操作
var yy = document.getElementById('tab').getElementsByTagName('input');
Run Code Online (Sandbox Code Playgroud)
我得到了我想要的东西 this.elem.nativeElement.children[0].children
这给了我一系列tr元素,我从中检查输入框
在角度2中有更好的方法吗?
yur*_*zui 15
更改html(添加#cbx到input),如:
<tr *ngFor="let val of valArray"><input #cbx type="checkbox" [value]="val"></tr>
Run Code Online (Sandbox Code Playgroud)
然后在你的组件类中:
@ViewChildren('cbx') checkboxes;
getChecked = () => {
console.log(this.checkboxes.toArray().map(x => x.nativeElement));
}
Run Code Online (Sandbox Code Playgroud)
它将打印所需复选框的数组
另见现场Plunker示例
更新
另一种方法是直接使用dom api:
@ViewChild ('tab') elem;
getChecked = () => {
console.log(this.elem.nativeElement.getElementsByTagName('input'));
console.log(this.elem.nativeElement.querySelectorAll('input'));
}
Run Code Online (Sandbox Code Playgroud)