1

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.

utvikla
  • 11
  • 2

1 Answers1

0

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
 });
}
Kavinda Senarathne
  • 1,813
  • 13
  • 15
  • Any suggestion on how to make the sorting logic? I've tried to make an extra array that defines the order of the states. But I'm not allowed to compare the indexes with the items state variable. – utvikla Mar 19 '21 at 11:34