Angular 7: Sorting Mat-Table with data from service as a MatTableDataSource

Viewed 1794

I am trying to sort a table MatSort in Angular 7, and am new to angular. Data is in the dataSource and is displaying properly. My data is coming from a service I made to call my back end, then I set this.dataSource.sort = this.sort, as showing in the following example:

https://stackblitz.com/angular/qlbmkgjnvya?file=main.ts (from angular docs!)

I've tried to follow the example from the angular docs, but I feel like I'm missing something since the sorting does nothing on my example, but when I take their example and use it locally it works fine.

// component

    import {MatSort} from '@angular/material/sort';
    ...
    dataSource: MatTableDataSource<any[]>;
    @ViewChild(MatSort) sort: MatSort;
    ...
    ngOnInit() {
    this.api.getData().subscribe(data => {
      this.data= data; // this is an array of the data
      this.dataSource = new MatTableDataSource(this.data); // works enough to display on the page without errors
      this.dataSource.sort = this.sort; // has to be in here to ensure no race condition between the api call and setting the sort property
   });

//view (component.html)

<table mat-table #table [dataSource]="dataSource" matSort>

  <!-- Title Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
    <td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

No error messages are displayed, but table is not updating.

2 Answers

If your data names do not match your column names, the sort function doesn't know what data to sort on so it ends up doing nothing (?) and not throwing an error. Don't know why I didn't think about this sooner.

I had the same issue and solved it once I changed the columns to respect the display columns as follows:

 displayedColumns: string[] = ['dataID'];

<table mat-table #table [dataSource]="dataSource" matSort>

  <!-- Title Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> data ID </th>
    <td mat-cell *matCellDef="let element" class="id-col"> {{element.dataID}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Related