Search code examples
angularangular-componentsmat-table

How to trigger mat-table sort programatically?


I have a table using mat-sort with a custom sortingDataAccessor to be able to sort on some nested data within the element (unsure if relevant). This works fine, the data is sorted, the problem occurs when the data is updated asynchronously, because now the data is no longer in order, since it's changed and the table hasn't updated it's order.

So how can I trigger the sort programatically? Or rather, how can I keep the table sorted at all times even if the dataSource.data gets updated?

Stackblitz to showcase problem: https://stackblitz.com/edit/angular-qoytbq

Thanks!


Solution

  • I'm not sure wether this is the official way (and there might be non according to this question), but setting the sort property to the MatTableDataSource to null before reassigning the previous MatSort seems to do the trick

      @ViewChild(MatSort, {static: true}) sort: MatSort;
    
      //Change table data here...
      //Trigger sort manually
      this.dataSource.sort = null;
      this.dataSource.sort = this.sort;
    

    Stackblitz demo

    Note: angular material does not look for changes to the underlying sources, as per this github issue comment

    When passing an array to the table, it will only re-render if the array reference is changed because it is based on the principle of using an immutable data array.

    An easy workaround is to re-assign the source's data property when the underlying data changes

    this.datasource.data = [...ELEMENT_DATA];//For your stackblitz