如何对Angular Material表格的对象按isGroupBy属性进行排序
Angular Material表格按isGroupBy属性排序实现方案
你的数据源为「分组头行(带isGroupBy属性)+ 所属子数据行(无isGroupBy属性)」的混合结构,排序需要保证分组头顺序符合要求的同时,子数据始终跟随对应分组头,具体实现步骤如下:
步骤1:组件内自定义排序逻辑
直接覆盖MatTableDataSource自带的默认排序规则,适配混合结构的排序需求:
import { MatSort, Sort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; export class YourComponent implements AfterViewInit { // 替换为你的实际列名配置 displayedColumns: string[] = ['yourColumn']; // 初始化数据源,填入你的原始数据 dataSource = new MatTableDataSource<any>(yourOriginalData); @ViewChild(MatSort) sort!: MatSort; ngAfterViewInit() { this.dataSource.sort = this.sort; // 自定义排序逻辑 this.dataSource.sortData = (data: any[], sort: Sort) => { // 第一步:给所有数据绑定所属分组标记,避免排序时子数据和分组头脱节 const processedData = data.reduce((acc, item) => { if (item.isGroupBy) { acc.currentGroup = item.isGroupBy; acc.result.push({...item, _groupKey: item.isGroupBy, _isGroupHeader: true}); } else { acc.result.push({...item, _groupKey: acc.currentGroup, _isGroupHeader: false}); } return acc; }, {currentGroup: '', result: []}).result; const isAsc = sort.direction === 'asc'; // 第二步:按规则排序 return processedData.sort((a, b) => { // 优先按分组key排序 if (a._groupKey < b._groupKey) return isAsc ? -1 : 1; if (a._groupKey > b._groupKey) return isAsc ? 1 : -1; // 同一分组内,分组头永远排在子数据前面 if (a._isGroupHeader && !b._isGroupHeader) return -1; if (!a._isGroupHeader && b._isGroupHeader) return 1; // 同类型数据可自定义其他排序规则,示例按id升序 return a.id - b.id; }); }; } }
步骤2:模板中绑定排序触发控件
给表格绑定matSort指令,给需要触发排序的表头加上mat-sort-header属性:
<table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="yourColumn"> <th mat-header-cell *matHeaderCellDef mat-sort-header> 列展示名称 </th> <td mat-cell *matCellDef="let element"> <!-- 分组头可单独做样式区分 --> <strong *ngIf="element.isGroupBy">{{element.isGroupBy}}</strong> <span *ngIf="!element.isGroupBy">{{element.你要展示的字段名}}</span> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
可选优化:自定义分组排序优先级
如果需要按自定义业务规则调整分组排序顺序(而非默认字符串排序),可以提前定义分组优先级映射:
// 自定义分组优先级,数字越小排越靠前 const groupPriority = { 'Anchorage': 1, 'Berth 1': 2, 'Berth 2': 3 }; // 把排序逻辑里的分组key比较替换为优先级比较即可 if (groupPriority[a._groupKey] < groupPriority[b._groupKey]) return isAsc ? -1 : 1;
内容的提问来源于stack exchange,提问作者divya dave
相关产品推荐
相关产品推荐

