MatTableDataSource how to get sorted order of data set?

Viewed 1167

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?

3 Answers

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)

You can access the new position o pass to a new array after filter sort the table;

 // let yourNewData = [ ... this.dataSource.filteredData]

 ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    console.log(this.dataSource.filteredData[0])
  }

Solution found here: https://github.com/angular/components/issues/11670

this.dataSource.connect().subscribe(d => this.renderedData = d);

In fact, what i did was that (recreate the table with the new row order):

this.dataSource.connect().subscribe(data: any) => this.dataSource = new MatTableDataSource(data));
Related