Issue
Let say I have a mat-table
with mat-sort-header
and matSort
to enable the sorting, and with [dataSource]="tableDetails"
. After I fetch the data into sampleData
, I initialize the table with following:
this.tableDetails = new MatTableDataSource(this.sampleData);
I have the sample data as below, and in it's default order:
sampleData =
[
{'id':1, 'name':'item 1'},
{'id':2, 'name':'item 2'},
{'id':3, 'name':'item 3'}
]
I can get the first item with this.tableDetails.data[0]
. Now if I use mat-sort-header
to sort the table with id
in descending order, the first item displayed will be {'id':3, 'name':'item 3'}
, but this.tableDetails.data[0]
still return the {'id':1, 'name':'item 1'}
. I notice that mat-sort-header will not change the original order of the datasource. Any idea on how to get the sorted order?
Solution
On the dataSource you have a sortData method which you can use to get sorted table data.
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)
Answered By - Adrian Sawicki
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.