Angular mat-table生成的复选框如何将对应execution数据传递到TS
解决方案
问题根源
你的写法存在两个核心问题:
- 多个元素复用了同一个
#checkBox模板引用变量,作用域冲突导致读取值异常 execution是*matCellDef提供的行级上下文变量,仅在当前行的单元格作用域内可用,你的提交按钮在表头区域,不在行作用域下,直接传execution必然返回undefined
实现步骤
我们可以直接使用Angular Material内置的SelectionModel处理选中逻辑,无需手动维护选中状态:
1. 修改TS代码
import { SelectionModel } from '@angular/cdk/collections'; import { MatTableDataSource } from '@angular/material/table'; // 建议先定义你的Execution类型,替换下方any export interface Execution { process: string; // 其他字段自行补充 } dataSource$ = new MatTableDataSource<Execution>(); // 初始化多选模型,第一个参数true代表允许多选 selection = new SelectionModel<Execution>(true, []); reprocessHomeProcesses() { // 这里直接拿到所有选中的execution对象数组 const selectedList = this.selection.selected; console.log(selectedList); // 后续调用API的逻辑写在这里即可 }
2. 修改HTML代码
<mat-table [dataSource]="dataSource$"> <ng-container matColumnDef="process"> <mat-header-cell *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]="selection.isSelected(execution)" (change)="selection.toggle(execution)" ></mat-checkbox> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>
你的问题解答
- 如何判断哪些复选框被选中:调用
selection.isSelected(execution)即可判断对应行的复选框是否选中,所有选中项可通过selection.selected直接获取。 - 如何将选中的execution传递到TS:
SelectionModel中存储的就是每行完整的execution对象,无需额外传参,在提交方法中直接读取this.selection.selected就能拿到所有选中的行数据。
内容的提问来源于stack exchange,提问作者benmessi12040
相关产品推荐
相关产品推荐

