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

刷新MatTableDataSource致选中行丢失,如何保留选中状态?

解决Angular Material表格重新赋值后单选状态丢失的问题

问题原因

Angular Material的SelectionModel是通过对象引用判断选中状态的。当你重新创建MatTableDataSource并赋值时,新数据源里的Schedule对象和之前选中的对象并非同一引用,导致表格无法识别原选中项,进而丢失选中样式。

解决方法

核心思路:先保存原选中项的唯一标识(比如ID),更新数据源后,从新数据中找到对应标识的对象,重新将其设为选中状态。

具体步骤:

  1. 更新数据前,记录当前选中项的唯一标识
  2. 重新赋值dataSource
  3. 从新数据源中匹配对应标识的对象,调用select方法恢复选中状态

示例代码:

// 1. 保存选中项的ID(假设Schedule有id属性)
const selectedScheduleId = this.selection.selected[0]?.id;

// 2. 修改Schedule数据后,重新赋值dataSource
this.schedules = updatedSchedules; // updatedSchedules为修改后的数组
this.dataSource = new MatTableDataSource(this.schedules);

// 3. 从新数据中找到对应项并恢复选中状态
if (selectedScheduleId) {
  const targetSchedule = this.dataSource.data.find(schedule => schedule.id === selectedScheduleId);
  if (targetSchedule) {
    this.selection.select(targetSchedule);
  }
}

额外优化

若不想每次重新创建MatTableDataSource,可直接更新其data属性减少不必要的实例化,核心的选中状态恢复逻辑保持不变:

// 直接更新data属性而非重新创建实例
this.dataSource.data = updatedSchedules;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:10:25