Angular Mat-table排序后当前页全选功能异常问题排查
Angular Mat-table 当前页全选功能修复方案
需求说明
- 已完成Mat-table分页配置,需实现当前页全选功能
- 排序后仅选中当前页面显示的记录
- 点击表头(如name列)时取消全选
现有问题
排序后点击全选按钮,后台实际选中了多页数据,但视觉上仅显示当前页记录选中,导致选中状态与实际数据不符。
问题原因
原selectRows方法直接操作this.dataSource.data(原始全量未排序数据),排序后当前页显示的是经过排序后的数据集,并非原始数组的前pageSize项,因此会错误选中其他页面的行。
修复代码
核心方法修改
- 选中当前页所有行
selectRows() { const displayedData = this.dataSource.filteredData; const startIndex = this.dataSource.paginator.pageIndex * this.dataSource.paginator.pageSize; const endIndex = startIndex + this.dataSource.paginator.pageSize; for (let index = startIndex; index < endIndex && index < displayedData.length; index++) { this.selection.select(displayedData[index]); } this.selectionAmount = this.selection.selected.length; }
- 判断当前页是否全选
isAllSelected() { const displayedData = this.dataSource.filteredData; const startIndex = this.dataSource.paginator.pageIndex * this.dataSource.paginator.pageSize; const endIndex = startIndex + this.dataSource.paginator.pageSize; const currentPageRows = displayedData.slice(startIndex, endIndex); return currentPageRows.every(row => this.selection.isSelected(row)); }
- 表头点击取消全选(优化状态同步)
onHeaderClick() { this.selection.clear(); this.selectionAmount = 0; }
修复逻辑说明
- 使用
dataSource.filteredData获取经过排序/过滤后的实时显示数据集,确保操作的是当前页面展示的数据 - 通过分页器的
pageIndex和pageSize计算当前页的索引范围,精准定位当前页的行数据 - 同步修改
isAllSelected方法的判断逻辑,仅校验当前页的行是否全部选中,保证全选按钮的状态正确
内容的提问来源于stack exchange,提问作者SK.
相关产品推荐
相关产品推荐

