需要在使用 renderRows() 方法的时候手动重新排序表格。具体实现方法如下:
import { MatSort } from "@angular/material/sort";
export class MyComponent implements OnInit { @ViewChild(MatSort) sort: MatSort;
ngOnInit(): void { this.dataSource.sort = this.sort; this.dataSource.sortingDataAccessor = (item, property) => { switch (property) { case "name": return item.name; case "age": return item.age; // ... default: return item[property]; } }; this.dataSource.sort.direction = "asc"; this.dataSource.sort.active = "name"; this.dataSource.sort.sortChange.subscribe(() => { this.dataSource.data = this.dataSource.data.slice(); // to trigger sorting }); this.dataSource.data = this.myDataService.getData(); // assuming a data service this.dataSource.sort.sort({id: "name", start: "asc"}); this.dataSource.paginator = this.paginator; this.dataSource.connect().subscribe(() => this.table.renderRows()); } }
在 ngOnInit 函数中,除了初始化 matSort 对象外,我们调用了两个方法来设置表格的排序方式:sortingDataAccessor 和 sort。sortingDataAccessor 是一个自定义函数,用于指定要排序的属性,因为 matSort 不支持嵌套属性。
我们还订阅了 sortChange 事件,以便可以手动触发 dataSource.data 的切片,从而重新排序数据。
最后,我们将 dataSource.data 连接到表格,以确保在排序或分页时刷新表格的显示。
这样,我们就可以在 Angular Material 表格中正确使用 renderRows() 方法和 matSort。