How to make a custom sort in MatTable Angular

1.1k Views Asked by At

I use MatTableDataSource filled with objects to populate a MatTable and want to make a custom sort on a string variable of the objects that represents the states the objects have.

I've managed to sort the variable by asc with MatSort, but want to change it to a custom sort that I define. This is the code I have for the sort and its working:

sortData(sort: Sort) {
    const data = this.datasource.data.slice();
    
    this.datasource.data = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'ObjectState': return compare(a.ObjectState, b.ObjectState, isAsc);
        case 'ObjectStateColor': return compare(a.ObjectState, b.ObjectState, isAsc);
        default: return 0;
      }
    });
  
    function compare(a: number | string, b: number | string, isAsc: boolean) {
      return this.a(a < b ? -1 : 1) * (isAsc ? 1 : -1);
    }
  }

How can I make a custom sort on the ObjectState variable?

Update:

I tried to make the sorting logic like this

return data.sort((a: Object, b: Object => {
        return this.objectStatesDefinedOrder.indexOf(a.ObjectState) - this.objectStatesDefinedOrder.indexOf(b.ObjectState);
      });
}

Where the objectStateDefinedOrder is an array with the states in strings in the right order.

But I get error on the whole line inside datasort: ',' expected.

1

There are 1 best solutions below

1
Kavinda Senarathne On

You will have to overwrite the sortData on your MatTableDataSource attached to the table. This is the function that is responsible for sorting records, e.g.

this.dataSource.sortData = (data: YourObjectType[], sort: MatSort) => {
 return data.sort((a: YourObjectType, b: YourObjectType => {
   //Sorting logic here
 });
}