I have a table which has a column that contains a checkbox for each row using *ngFor
. Upon clicking a button I want to uncheck all the checkboxes. I tried using [(ngModel)]="boxChecked"
for each checkbox and setting that value to false in the method that my button click calls but that results in each checkbox being checked whenever I check only one of them. This does uncheck all checkboxes upon button click but I still need to be able to individually check the checkboxes.
<ng-template pTemplate="body" let-sub let-expanded="expanded" let-columns="columns">
<tr [pSelectableRow]="subcontract">
<td *ngFor="let col of columns" [ngSwitch]="true" style="text-align: center">
<div *ngSwitchCase="col.export" ><input type="checkbox" (change)="checked($event, sub)" [(ngModel)]="boxChecked"></div>
</td>
</tr>
</ng-template>
<button type="button"(click)="reset(table)"></button>
ts:
//I send the ID of the table to this method.
reset(table) {
table.reset();
this.boxChecked = false;
}
So far in my research I don't see that there is a get(index i)
(to get a single row of the index parameter) method of some sort on my table. Then I could easily just loop through my table and set the checkbox of each iteration(row) to false.
Since the check boxes are not bound to a property (which could be reset to uncheck the box), you can use a template reference variable (e.g. #checkboxes
):
<input #checkboxes type="checkbox" ...>
...
<button type="button" (click)="uncheckAll()"></button>
to retrieve the check boxes with ViewChildren
in the code and uncheck each one:
@ViewChildren("checkboxes") checkboxes: QueryList<ElementRef>;
uncheckAll() {
this.checkboxes.forEach((element) => {
element.nativeElement.checked = false;
});
}
See this stackblitz for a demo.
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