我要与mat-table一起使用的数据不是平坦的-有多层不同的对象。我可以很好地显示数据,但排序不起作用。这是一个使用元素数据的示例,其中字段位于“ foo”对象内的一层下。我如何才能进行排序?
https://stackblitz.com/edit/angular-b8u3zr?file=src%2Fapp%2Ftable-sorting-example.ts
const ELEMENT_DATA: PeriodicElement[] = [
{foo: {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}},
{foo: {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}},
{foo: {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}},
...
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container matColumnDef="foo.position">
<th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
<td mat-cell *matCellDef="let element"> {{element.foo.position}} </td>
</ng-container>
...
</table>
答案 0 :(得分:1)
根据docs(检查api标签,并搜索排序自定义)
通过覆盖sortingDataAccessor允许排序自定义, 定义如何访问数据属性。还允许过滤器 通过覆盖filterTermAccessor进行自定义,后者定义行的方式 数据将转换为字符串以进行过滤器匹配。
这就是您所需要的,您需要添加类型的sortData函数
sortData: ((data: T[], sort: MatSort) => T[])
这是一个示例
@ViewChild(MatSort, {static: true}) sort: MatSort;
ngOnInit() {
this.dataSource.sort = this.sort;
this.dataSource.sortData = this.sortData;
}
sortData(data: PeriodicElement[],sort: MatSort): PeriodicElement[] {
if (!sort.active || sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
// Add other cases (columns)
// if you are wondering where is this 'position' coming from, check the html tag for the th below
case 'position': return isAsc ?
(a.foo.position - b.foo.position > 1 ? 1 : -1) :
(a.foo.position - b.foo.position > 1 ? -1 : 1);
default: return 0;
}
});
}}
HTML
<th mat-header-cell *matHeaderCellDef mat-sort-header='position'> No. </th>