In my application, there are 3 checkboxes along with a master checkbox that allows users to select or deselect all of them at once.
Everything works fine with the master checkbox until I delete some rows from the table. After deleting data, I can check the master checkbox to select all the remaining checkboxes, but then I encounter an issue when trying to deselect them. Here is a visual representation:
https://i.stack.imgur.com/tzd9e.gif
<table mat-table [dataSource]="serviceTable" #matTableService class="mat-elevation-z8">
<!-- Checkbox Column -->
<ng-container matColumnDef="select">
<th style="width: 200px" mat-header-cell *matHeaderCellDef>
<mat-checkbox [checked]="selection.hasValue() && isAllSelected()" (change)="toggleAllServices()" [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox [checked]="selection.isSelected(row)" (change)="selection.toggle(row)"> </mat-checkbox>
</td>
</ng-container>
selection = new SelectionModel<Services>(true, []);
toggleAllServices(): void {
console.log(this.selection.selected, 'selected')
console.log(this.serviceTable, 'services');
if (this.isAllSelected()) {
this.selection.clear();
this.allServicesAreSelected = false;
return;
}
this.selection.select(... this.serviceTable);
this.allServicesAreSelected = true;
}
isAllSelected(): boolean {
return this.selection.selected.length === this.serviceTable.length
}
When I need to delete rows, I use the following method:
deleteMultipleServices():void {
const SELECTED_IDS:Array<number> = [];
for (let item of this.selection.selected) {
SELECTED_IDS.push(item.id);
}
this.serviceTable = this.serviceTable.filter((serviceValue, i) => !SELECTED_IDS.includes(i))
this.matTableService.renderRows();
}
My problem arises after deleting a row - the if-statement if (this.isAllSelected()) {
is never triggered. This is because this.serviceTable
correctly returns 2 objects, but this.selection.selected
still shows 3 objects even though one has been deleted. How can I solve this discrepancy?