如何以编程方式设置 mat-table 中 mat-checkbox 的检查状态?

How to programmatically set check state of mat-checkbox in mat-table?

我正在使用 Angular 和 material,具体来说,我正在使用 mat-table 构建一个 table。 我的 table 很简单,有两列 - 名称列和“select”列(复选框)。

这是我的 table 组件代码:

    <mat-table #table [dataSource]="dataSource" matSort matSortActive="name">
  
      <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
      </ng-container>
  
      <ng-container matColumnDef="select">
        <mat-header-cell *matHeaderCellDef> Select </mat-header-cell>
        <mat-cell *matCellDef="let element"> 
        
          <mat-checkbox #checkBox [value]="element.position"(change)="getCheckbox(checkBox)"></mat-checkbox>
        
        </mat-cell>
      </ng-container>
  
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row (click)="setCheckedState()" *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>

然后我使用以下代码收集已检查项目的列表:

  @ViewChildren ('checkBox') checkBox: QueryList<any> | undefined;

  checked: any = [];

  getCheckbox(checkbox: any){
    this.checked = []; // resetting each Time new event is fire.
    // filtering only checked vlaue and assign to checked variable.
    const checked = this.checkBox?.filter(checkbox => checkbox.checked);

    // then, we make object array of checked, and value by checked variable  
    checked?.forEach(data => {
      this.checked.push ({ 
        'checked' : data.checked,
        'value':  data.value
      });
    });
  }

获取选中项目列表的 Stackbliz 示例:https://stackblitz.com/edit/angular-efyvdr?file=src%2Fapp%2Fapp.component.html

mat-table 上,我希望能够做的是单击该行以设置该行复选框的选中状态。

我试过设置行的点击(确实会触发),但似乎无法选中该行的复选框。如何根据mat-row点击设置checked状态(true/false)?

提前感谢您的指点!

最简单的方法是创建一个 class 来保存复选框的名称和状态,类似于:

export class ItemStatus {
  name: string;
  checked: boolean;
  id: number;

  constructor(id, name) {
    this.id = id;
    this.name = name;
    this.checked = false;
  }
}

然后,您改为使用 [(ngModel)] 而不是 [value],如下所示:<mat-checkbox [(ngModel)]="element.checked">

然后最后,将get checked函数更改为根据已检查状态进行过滤,如下所示:

getCheckedItems() {
   this.checked = this.items.filter(i => i.checked == true);
}

总而言之,这是一个堆栈闪电战: https://stackblitz.com/edit/angular-gg394h?file=src%2Fapp%2Fapp.component.html