简体   繁体   English

无法在每次点击时获得选中的 mat-checkbox

[英]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.我在表格中使用mat-checkbox并且我想在每次单击或选择更改复选框组时调用 selection() 方法。 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. html:以下所有方法都是该组件的默认实现。

<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: 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) {

}

try something like this尝试这样的事情

in html:在 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:在 ts:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM