I looked for answers to this problem but I'm still stuck I have a table with multiple rows with a checkbox on every row, I need a checkbox to select all and deselect all, here some example code
Template
<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" (change)="checkAll($event)"/>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let size of sizes | async ; 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}}"/>
</td>
</tr>
</tbody>
Component
export class ListSizeComponent implements OnInit {
constructor () {
}
sizes: any;
setSizes() {
this.sizes = [
{'size': '0', 'diameter': '16000 km'},
{'size': '1', 'diameter': '32000 km'}
]
}
checkAll(ev) {
if (ev.target.checked) {
console.log("True")
} else {
console.log("False");
}
}
ngOnInit(): void {
this.setSizes();
}
}
You can leverage ngModel
to do that.
Template:
<input type="checkbox" name="all" [checked]="isAllChecked()" (change)="checkAll($event)"/>
....
<input type="checkbox" name="sizecb[]" value="{{size.id}}" [(ngModel)]="size.state"/>
Component:
checkAll(ev) {
this.sizes.forEach(x => x.state = ev.target.checked)
}
isAllChecked() {
return this.sizes.every(_ => _.state);
}
Stackblitz Example
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