1

我使用填充了对象的 MatTableDataSource 来填充 MatTable,并希望对表示对象具有的状态的对象的字符串变量进行自定义排序。

我已经设法使用 MatSort 按 asc 对变量进行排序,但想将其更改为我定义的自定义排序。这是我用于排序及其工作的代码:

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);
    }
  }

如何对 ObjectState 变量进行自定义排序?

更新:

我试图使排序逻辑像这样

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

其中 objectStateDefinedOrder 是一个数组,其中字符串中的状态以正确的顺序排列。

但我在 datasort: ',' 预期的整行上得到错误。

4

1 回答 1

0

sortData您将不得不覆盖MatTableDataSource附在表格上的 。这是负责对记录进行排序的函数,例如

this.dataSource.sortData = (data: YourObjectType[], sort: MatSort) => {
 return data.sort((a: YourObjectType, b: YourObjectType => {
   //Sorting logic here
 });
}
于 2021-03-19T10:49:26.047 回答