Search code examples
javascriptangulartypescriptangular-materialmat-table

Cannot get selected mat-checkbox on each click


I use mat-checkbox in a table and I want to call a selection() method on each click or selected change of a checkbox group. However, the default definitions are used in order to check if all selected or not. So, how can I call my custom method and get only the selected records? Current implementation returns previously selected checkboxes also.

html: All the methods below are default implementation of that component.

<ng-container matColumnDef="select">
  <th mat-header-cell *matHeaderCellDef>

    <!-- header -->
    <mat-checkbox (change)="$event ? masterToggle() : null"
                  [checked]="selection.hasValue() && isAllSelected()"
                  [indeterminate]="selection.hasValue() && !isAllSelected()">
    </mat-checkbox>
  </th>

  
  <!-- rows -->
  <td mat-cell *matCellDef="let row">
    <mat-checkbox (click)="$event.stopPropagation()"
                  (change)="$event ? selection.toggle(row) : null"
                  [checked]="selection.isSelected(row)">
    </mat-checkbox>
  </td>
</ng-container>

ts:

isAllSelected() {
  const numSelected = this.selection.selected.length;
  const numRows = this.data.length;
  return numSelected === numRows;
}


masterToggle() {

  if (this.isAllSelected()) {
    this.selection.clear();
  }
  else {
      this.tableDataSource.forEach(row => this.selection.select(row));
  }
}

//here is the cstom method that I want to call on every selection change
selectionCh(sel) {

}

Solution

  • try something like this

    in html:

    <!-- rows -->
    <td mat-cell *matCellDef="let row">
        <mat-checkbox (click)="selectionCh($event)"
                  (change)="$event ? selection.toggle(row) : null"
                  [checked]="selection.isSelected(row)">
        </mat-checkbox>
     </td>
    

    in ts:

    selectionCh($event) {
        $event.stopPropagation();
        let value = $event.target.checked;
        /* iterate over the rows to see which ones are selected 
         * and implement your logic
         */
    }