带Rowspan的Material Table启用分页后出现值重复问题如何解决
带rowspan的Material Table分页重复问题解决方案
问题原因
出现重复问题是因为rowspan的计算逻辑没有和分页后的切片数据做适配:默认是基于全量数据统计的合并行数,分页器对数据源做切片后,原本的合并判断逻辑(比如是否为同组首行)无法正确适配当前页的局部行索引,导致同组数据跨分页边界时出现重复渲染。
修复方案
1. 预加工全量数据
先对完整的数据源做分组打标,给每一条拆分后的渲染行添加两个控制属性:
needShow:标记当前行是否需要渲染带合并的列单元格rowspan:标记当前行对应的合并行数
示例代码:
interface ProcessedRow { id: number; name: string; weight: number; currentDesc: string; needShow: boolean; rowspan: number; } // 原始数据转成可直接渲染的行数据 processRawData(rawData: any[]): ProcessedRow[] { const result: ProcessedRow[] = []; rawData.forEach(item => { // 有多少条描述就拆分多少行 const descLength = item.descriptions.length; item.descriptions.forEach((desc, index) => { result.push({ ...item, currentDesc: desc, // 只有同组的第一行需要显示合并列 needShow: index === 0, rowspan: descLength }) }) }) return result; }
2. 配置表格渲染逻辑
带合并的列添加渲染判断,只有needShow为true时才渲染单元格,同时绑定rowspan属性:
<ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef> 名称 </th> <td mat-cell *matCellDef="let row" *ngIf="row.needShow" [attr.rowspan]="row.rowspan" > {{row.name}} </td> </ng-container> <ng-container matColumnDef="weight"> <th mat-header-cell *matHeaderCellDef> 重量 </th> <td mat-cell *matCellDef="let row" *ngIf="row.needShow" [attr.rowspan]="row.rowspan" > {{row.weight}} </td> </ng-container> <!-- 不需要合并的描述列正常渲染即可 --> <ng-container matColumnDef="description"> <th mat-header-cell *matHeaderCellDef> 描述 </th> <td mat-cell *matCellDef="let row"> {{row.currentDesc}} </td> </ng-container>
3. 配置行唯一标识避免复用异常
给mat-table添加trackBy配置,防止分页时行复用导致的渲染错乱:
<table mat-table [dataSource]="dataSource" [trackBy]="trackByRow" [matSort]="sort" >
对应的TS逻辑:
trackByRow(index: number, row: ProcessedRow): string { // 用id加当前描述保证每一行的唯一标识 return `${row.id}-${row.currentDesc}`; }
按以上逻辑调整后,分页时只会对已经打好标记的全量数据做切片,合并逻辑不受分页影响,不会再出现重复值问题。
内容的提问来源于stack exchange,提问作者Pyaru
相关产品推荐
相关产品推荐

