刷新MatTableDataSource致选中行丢失,如何保留选中状态?
解决Angular Material表格重新赋值后单选状态丢失的问题
问题原因
Angular Material的SelectionModel是通过对象引用判断选中状态的。当你重新创建MatTableDataSource并赋值时,新数据源里的Schedule对象和之前选中的对象并非同一引用,导致表格无法识别原选中项,进而丢失选中样式。
解决方法
核心思路:先保存原选中项的唯一标识(比如ID),更新数据源后,从新数据中找到对应标识的对象,重新将其设为选中状态。
具体步骤:
- 更新数据前,记录当前选中项的唯一标识
- 重新赋值
dataSource - 从新数据源中匹配对应标识的对象,调用
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
相关产品推荐
相关产品推荐

