首页 > 解决方案 > 有没有办法根据Angular中的单元格值对表格进行排序?

问题描述

我当前的表格如下所示:

地位
草稿
待办的
完全的

我想根据单元格的值对它们进行排序。有没有办法做到这一点?我只能使用以下代码对它们进行排序:

    onChange(status: string){
      const sortState: Sort = {active: status, direction: 'desc'};
      this.sort.active = sortState.active;
      this.sort.direction = sortState.direction;
      this.sort.sortChange.emit(sortState);
    }

但我想使用状态本身的值进行排序,因为我想创建一个按钮,单击该按钮时从完成或草稿或待处理开始排序。

标签: htmlangulartypescriptangular-material

解决方案


我对你的问题有点困惑,但我想我明白你在问什么。您需要将值转换为数组,然后使用该.sort()函数。因此,假设您有一个单元格数组,我们可以调用它let array = Cell[],然后您可以像这样访问单元格的状态:

sortCells(){
 let array = Cell[]; // here we're assuming there is already a cell type and a cell.active parameter, like shown in your example.
 let possibleValues = ["Draft","Pending","Complete"]; // easier way to compare two values
 array.sort((a,b)=>{
 let aIndex = possibleValues.indexOf(a.active); // index of gets the location of the element in an array
 let bIndex = possibleValues.indexOf(b.active);

  if(a > b){
   return -1;
  } else if(b > a){
   return 1;
  }else{
   return 0; // they are equal
  }

})
}

您可以在此处阅读有关排序的更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


推荐阅读