You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用mat-table时无法将DataSource的行数据传递到TypeScript如何解决?

无法获取execution的根本原因

你把传递execution参数的按钮放在了<mat-header-cell>表头单元格节点内,execution是*matCellDef提供的行级作用域变量,仅在每一行的单元格(<mat-cell>)范围内有效,表头作用域不存在该变量,因此传递的参数天然为undefined,而行内的{{execution.process}}处于行作用域内,所以可以正常渲染。


实现多选提交的解决方案

我们通过存储选中项数组的方式实现需求,修改代码如下:

1. TypeScript 部分新增变量与方法

首先定义选中项存储数组,以及复选框状态变更、提交的处理逻辑:

import { MatCheckboxChange } from '@angular/material/checkbox';

// 类中定义选中项数组,可替换为你实际的Execution类型
selectedProcesses: any[] = [];

// 复选框状态变更处理
onCheckChange(event: MatCheckboxChange, execution: any) {
  if (event.checked) {
    this.selectedProcesses.push(execution);
  } else {
    // 替换为你数据中唯一标识条目的字段即可,无id可以换为process
    const targetIndex = this.selectedProcesses.findIndex(item => item.id === execution.id);
    if (targetIndex > -1) {
      this.selectedProcesses.splice(targetIndex, 1);
    }
  }
}

// 提交方法直接读取选中数组即可
reprocessHomeProcesses() {
  // 打印所有选中的条目
  console.log(this.selectedProcesses);
  // 如需单独提取process字段:this.selectedProcesses.map(item => item.process)
  // 后续在此处发起API调用即可
}

2. 模板部分修改

调整复选框绑定与表头按钮的逻辑:

<mat-table [dataSource]="dataSource$">
  <ng-container matColumnDef="process">
    <mat-header-cell #checkBox *matHeaderCellDef> Process </mat-header-cell>
    <mat-cell *matCellDef="let execution"> {{execution.process}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef="reprocess">
    <mat-header-cell *matHeaderCellDef>  
       <button tslbutton class="tslbutton" (click)="reprocessHomeProcesses()" id="reprocessButton">
          Reprocess
       </button> 
    </mat-header-cell>
    <mat-cell id="reprocessCell" *matCellDef="let execution">
       <!-- 新增复选框状态绑定与变更事件 -->
       <mat-checkbox 
         class="checker"
         [checked]="selectedProcesses.some(item => item.id === execution.id)"
         (change)="onCheckChange($event, execution)"
       ></mat-checkbox>
    </mat-cell>
  </ng-container>
</mat-table>

内容的提问来源于stack exchange,提问作者benmessi12040

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:27:04