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

绑定element级datasource时MatTable复选框主开关如何适配selectionMap

适配方案

1. 初始化逻辑调整

在你给行元素挂载数据源的位置,同步给userSelectionMap初始化对应行ID的选择实例:

// 原有挂载数据源的逻辑
element['usersdataSource'] = new MatTableDataSource(res);
// 新增:为当前行初始化独立的选择器
this.userSelectionMap.set(element.Id, new SelectionModel<any>(true, []));

提示:如果你的行元素唯一标识字段不是Id,请替换为实际使用的字段名。

2. 主开关触发逻辑调整

将原方案中从全局数组取数据源的逻辑,改为直接从行元素自身属性读取数据源:

UserMasterToggle(element: any) {
  const currSelection = this.userSelectionMap.get(element.Id);
  // 处理未初始化的边界场景,避免报错
  if (!currSelection || !element.usersdataSource) return;

  this.isAllUserSelected(element.Id)
    ? currSelection.clear()
    : element.usersdataSource.data.forEach(row => currSelection.select(row));
}

3. 全选状态判断逻辑修正

原问题给出的全选判断逻辑不匹配多展开行场景,适配后逻辑如下:

isAllUserSelected(elementId: number): boolean {
  const currSelection = this.userSelectionMap.get(elementId);
  // 从外层父表格的数据源中找到对应ID的行元素,此处yourOuterDataSource请替换为实际的父表格数据源变量名
  const targetParentRow = this.yourOuterDataSource.data.find(item => item.Id === elementId);
  
  if (!currSelection || !targetParentRow?.usersdataSource) return false;
  return currSelection.selected.length === targetParentRow.usersdataSource.data.length;
}

4. 模板绑定适配

子表格的复选框绑定对应调整即可:

<!-- 子表格全选主开关绑定,element为当前父行元素 -->
<mat-checkbox
  [checked]="isAllUserSelected(element.Id)"
  (change)="UserMasterToggle(element)"
>全选</mat-checkbox>

<!-- 子表格单行复选框绑定,row为子表格的当前行元素 -->
<mat-checkbox
  [checked]="userSelectionMap.get(element.Id)?.isSelected(row)"
  (change)="userSelectionMap.get(element.Id)?.toggle(row)"
>{{row.name}}</mat-checkbox>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:54:08