问题描述:使用 Angular Material v13 的表格组件时,发现无法进行排序操作。
解决步骤:
确保在表格组件中设置了 matSort
指令:
在组件中引入 MatSort
、MatSortable
以及 DataSource
组件:
import { MatSort, MatSortable } from '@angular/material/sort';
import { DataSource } from '@angular/cdk/collections';
在组件中使用以下代码定义 dataSource
变量,指定数据源和排序处理逻辑:
export class MyComponent implements OnInit {
dataSource: MyDataSource;
constructor(private myService: MyService) {}
ngOnInit() {
this.dataSource = new MyDataSource(this.myService);
}
}
export class MyDataSource extends DataSource {
constructor(private myService: MyService) { super(); }
sort: MatSortable = { id: 'defaultSort', start: 'asc' }; // 设置默认排序规则
connect(): Observable {
return this.myService.getData().pipe(
map(data => {
// 对数据进行排序处理
const sortedData = this.sortData(data, this.sort);
return sortedData;
})
);
}
disconnect() {}
// 排序处理逻辑
private sortData(data: MyData[], sort: MatSortable): MyData[] {
if (!sort.active || sort.direction === '') { return data; }
const sortedData = [...data].sort((a, b) => {
const isAsc = sort.direction === 'asc';
const x = a[sort.active];
const y = b[sort.active];
return this.compare(x, y, isAsc);
});
return sortedData;
}
// 排序比较函数
private compare(a: number | string, b: number | string, isAsc: boolean) {
return (