可以在 ngOnDestroy 生命周期中手动重置表格排序状态。首先,引入排序组件的 ViewChild,如下所示:
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ViewChild } from '@angular/core';
export class MyComponent implements OnInit, OnDestroy {
@ViewChild(MatSort, { static: true }) sort: MatSort;
dataSource = new MatTableDataSource();
sortedData;
ngOnInit() {
this.dataSource.sort = this.sort;
}
ngOnDestroy() {
this.dataSource.sort = null;
}
}
在 ngOnDestroy 生命周期中,将表格的 sort 属性设置为 null,这将重置表格的排序状态。