在这里,我尝试使用ngOnit选中所有复选框,但它正在调用该函数,并通过单击它在调用该函数,然后选择全部
.html代码
<div>
<h2>Hello Angular2</h2>
<table class="table table-bordered table-condensed table-striped table-hover">
<thead>
<tr>
<th></th>
<th>Size</th>
<th>Diameter</th>
<th class="text-center">
<input type="checkbox" name="all" [checked]="isAllChecked()" (change)="checkAll($event)"/>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let size of sizes ; let i = index">
<td class="text-right">{{i + 1}}</td>
<td class="text-right">{{size.size}}</td>
<td>{{size.diameter}}</td>
<td class="text-center">
<input type="checkbox" name="sizecb[]" value="{{size.id}}" [(ngModel)]="size.state"/>
</td>
</tr>
</tbody>
</table>
</div>
.ts代码:
sizes: any[] = [
{ 'size': '0', 'diameter': '16000 km' },
{ 'size': '1', 'diameter': '32000 km' }
];
checkAll(ev) {
this.sizes.forEach(x => x.state = ev.target.checked)
}
isAllChecked() {
debugger;
return this.sizes.every(_ => _.state);
}
ngOnInit() {
this.isAllChecked();
}
下面是我的堆栈闪电网址
答案 0 :(得分:1)
您的代码运行正常。缺少的事情是您在定义的数组中没有键state: true
。这就是为什么它没有选中所有复选框。
尝试此数组
sizes: any[] = [
{ 'size': '0', 'diameter': '16000 km', 'state': true },
{ 'size': '1', 'diameter': '32000 km', 'state': true }
];
答案 1 :(得分:0)
<div>
<h2>Hello Angular2</h2>
<table class="table table-bordered table-condensed table-striped table-hover">
<thead>
<tr>
<th></th>
<th>Size</th>
<th>Diameter</th>
<th class="text-center">
<input type="checkbox" name="all" [checked]="isAllChecked()" (change)="checkAll($event)"/>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let size of sizes ; let i = index">
<td class="text-right">{{i + 1}}</td>
<td class="text-right">{{size.size}}</td>
<td>{{size.diameter}}</td>
<td class="text-center">
<input type="checkbox" name={{sizecb + i}} value="{{size.id}}"
(change)="sizes[i].state = !sizes[i].state" [checked]="size.state" [(ngModel)]="size.state"/>
</td>
</tr>
</tbody>
</table>
</div>
and in ts
try this array
sizes: any[] = [
{ 'size': '0', 'diameter': '16000 km', 'state': true },
{ 'size': '1', 'diameter': '32000 km', 'state': true }
];