Search code examples
angularangular-materialmat-table

Angular material table renderRows() does not work with matSort


I'm implementing sorting and deletion/addition to a mat-table.

I have been reading this, which works fine without sorting.

When I use mat-table and matSort attributes on a table, renderRows() stops working.

StackBlitz

As soon as I remove the sorting attributes it works again.

I found an alternative solution but it would be good to know if I did something wrong, has someone else made it work, is it a bug or intended behaviour?

Doesn't work:

delete(index: number): void {
  this.dataSource.data.splice(index, 1);
  this.table.renderRows();
}

Does work:

delete(id: number): void {
  this.dataSource.data = this.dataSource.data.filter( (item: any) => item.id !== id);
}

Solution

  • after splice() by index of item, you should update the datasource.

    delete(id: number, index: number): void {
        this.dataSource.data.splice(index, 1);
        this.table.renderRows();
        this.dataSource._updateChangeSubscription();  // <-- Refresh the datasource
      }
    

    Working example link Stackblitz