Search code examples
angularangular-material

MatSort not working after selection of data source


I am working on this small app to show data based on a selection of a dropdown menu. Based upon the selection, a Angular Material table should be shown. This table should be sortable via MatSort, like in Angular Material's example.

The arrows for sorting are shown, but when clicking on them, nothing functional happens.

Table of functionality shown

Below is the (adjusted) sort function, I tried to assign it to selectedHomeData and to create a new array, but no avail. Probably I am missing something trivial when (re)assigning the data.

  sortData(sort: Sort) {
    const data = this.data;
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a: any, b: any) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name':
          return this.compare(a.name, b.name, isAsc);
        case 'goals':
          return this.compare(a.stats.goals, b.stats.goals, isAsc);
        default:
          return 0;
      }
    });
  }

I have created this StackBlitz as an example app of what my code currently looks like.


Solution

  • All you need to do is (notice the [...):

    sortData(sort: Sort) {
      ...
      this.selectedHomeData = [...this.selectedHomeData?.sort((a: any, b: any) => {
      ...
      })];
    }
    

    When you sort the dataSource, you must change the array pointer, i.e. copy the sorted array to another memory address so Angular will detect the change. The default sort() behavior is sorting in place, i.e. in the same memory address.