MatTableDataSource 如何获取数据集的排序顺序?
MatTableDataSource how to get sorted order of data set?
假设我有一个 mat-table
和 mat-sort-header
和 matSort
来启用排序,还有 [dataSource]="tableDetails"
。在我将数据提取到 sampleData
后,我用以下内容初始化 table:
this.tableDetails = new MatTableDataSource(this.sampleData);
我有如下示例数据,默认顺序为:
sampleData =
[
{'id':1, 'name':'item 1'},
{'id':2, 'name':'item 2'},
{'id':3, 'name':'item 3'}
]
我可以用 this.tableDetails.data[0]
得到第一个项目。现在如果我使用 mat-sort-header
将 table 与 id
降序排列,显示的第一项将是 {'id':3, 'name':'item 3'}
,但 this.tableDetails.data[0]
仍然是 return {'id':1, 'name':'item 1'}
。我注意到 mat-sort-header 不会改变数据源的原始顺序。关于如何获得排序顺序的任何想法?
在 dataSource 上,您有一个 sortData 方法,您可以使用该方法对 table 数据进行排序。
MatTableDataSource sortData method
Gets a sorted copy of the data array based on the state of the MatSort. Called after changes are made to the filtered data or when sort changes are emitted from MatSort. By default, the function retrieves the active sort and its direction and compares data by retrieving data using the sortingDataAccessor. May be overridden for a custom implementation of data ordering.
this.dataSource.sortData(this.dataSource.data, this.dataSource.sort)
您可以在过滤排序后访问新位置 o 传递给新数组 table;
// let yourNewData = [ ... this.dataSource.filteredData]
ngAfterViewInit() {
this.dataSource.sort = this.sort;
console.log(this.dataSource.filteredData[0])
}
假设我有一个 mat-table
和 mat-sort-header
和 matSort
来启用排序,还有 [dataSource]="tableDetails"
。在我将数据提取到 sampleData
后,我用以下内容初始化 table:
this.tableDetails = new MatTableDataSource(this.sampleData);
我有如下示例数据,默认顺序为:
sampleData =
[
{'id':1, 'name':'item 1'},
{'id':2, 'name':'item 2'},
{'id':3, 'name':'item 3'}
]
我可以用 this.tableDetails.data[0]
得到第一个项目。现在如果我使用 mat-sort-header
将 table 与 id
降序排列,显示的第一项将是 {'id':3, 'name':'item 3'}
,但 this.tableDetails.data[0]
仍然是 return {'id':1, 'name':'item 1'}
。我注意到 mat-sort-header 不会改变数据源的原始顺序。关于如何获得排序顺序的任何想法?
在 dataSource 上,您有一个 sortData 方法,您可以使用该方法对 table 数据进行排序。
MatTableDataSource sortData method
Gets a sorted copy of the data array based on the state of the MatSort. Called after changes are made to the filtered data or when sort changes are emitted from MatSort. By default, the function retrieves the active sort and its direction and compares data by retrieving data using the sortingDataAccessor. May be overridden for a custom implementation of data ordering.
this.dataSource.sortData(this.dataSource.data, this.dataSource.sort)
您可以在过滤排序后访问新位置 o 传递给新数组 table;
// let yourNewData = [ ... this.dataSource.filteredData]
ngAfterViewInit() {
this.dataSource.sort = this.sort;
console.log(this.dataSource.filteredData[0])
}