Home > Enterprise >  Not able to deselect all checlboxes, after delete
Not able to deselect all checlboxes, after delete

Time:05-31

I have 3 checkboxes and a master checkbox to select or deselect them all.

The master checkbox works fine until I delete some rows from my table. When some data has been deleted, I can check the master checkbox to select them all again but I am not able to deselect them. This is how it looks like:

enter image description here

<table mat-table [dataSource]="serviceTable" #matTableService >
  <!-- 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
}

This is how I delete:

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 is, as soon as I have deleted a row, I never get into the if-statement if (this.isAllSelected()) {, since this.serviceTable returns 2 objects, which is correct but this.selection.selected returns 3 objects, which is wrong since I have deleted one. Why is that and how can I fix it?

CodePudding user response:

Try it once -

<ng-container matColumnDef="select">
    <th style="width: 200px" mat-header-cell *matHeaderCellDef>
      <mat-checkbox [checked]="selection.hasValue() && isAllSelected()" (change)="$event ? toggleAllServices() : null" 
      [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox [checked]="selection.isSelected(row)" (change)="$event ? selection.toggle(row): null"> </mat-checkbox>
    </td>
  </ng-container>

CodePudding user response:

After you have deleted items, you should clear the selection.

This should do the magic:

this.selection.clear();
  • Related