如何使用行分组对PrimeNG DataTable中的数据进行排序

时间:2017-06-20 10:25:43

标签: angular primeng primeng-datatable

我想要做的是按照字母顺序或自定义顺序对已经分组的数据进行排序。我使用sortField属性来指定groupheader顺序,但我也需要在组内部对数据进行排序。

enter image description here

3 个答案:

答案 0 :(得分:1)

我有同样的问题。我添加了自定义排序来解决这个问题

添加自定义排序

<p-column   field="color" header="color"  sortable="custom" (sortFunction)="sortByColor($event)"></p-column>

在打字稿中创建一个customSort

sortByColor(e) {
    this.cars.sort(function (a, b) {
      let aGroup = a.name.toLowerCase();
      let bGroup = b.name.toLowerCase();
      if (aGroup > bGroup) return 1;
      if (aGroup < bGroup) return -1;
      let aSort = a.color.toLowerCase();
      let bSort = b.color.toLowerCase();
      if (aSort > bSort) return 1;
      if (aSort < bSort) return -1;
      return 0
    });
  }

答案 1 :(得分:1)

对于那些遇到TurboTable <p-table>问题的人,这里是解决方法:

<p-table sortField="name" sortMode="single" (onSort)="onSort($event)" (sortFunction)="customSort($event)" [customSort]="true">

OnSort()实现:

onSort() {
   // function to properly work with turbotable and rowgroup, see: https://www.primefaces.org/primeng/#/table/rowgroup 
   this.updateRowGroupMetaData();
}

customSort()实现:

customSort(e) {
  this.budgets.sort((a, b) => {
    const aGroup = a.name.toLowerCase();
    const bGroup = b.name.toLowerCase();
    if (aGroup > bGroup) { return 1; }
    if (aGroup < bGroup) { return -1; }
    const aSort = a.color;
    const bSort = b.color;
    if (aSort > bSort) { return 1; }
    if (aSort < bSort) { return -1; }
    return 0;
  });
}

答案 2 :(得分:0)

我遇到了同样的问题。我使用了自定义排序。下面是代码:

在模板中:

<p-column   field="color" header="color"  sortable="custom" (sortFunction)="sortByColor($event,sortOrder)"></p-column>

下面是typescript中的sortByColor函数:

  sortOrder = 1;//1 means ascending order, 2 means descending order
  sortByField(e, order) {   
    this.cars.Data.sort(function (a, b) {
      let aGroup = a.name.toLowerCase();
      let bGroup = b.name.toLowerCase();
      if (aGroup > bGroup) return 1;
      else if (aGroup < bGroup) return -1;
      let aSort = a.color.toLowerCase();
      let bSort = b.color.toLowerCase();
      if (aGroup == bGroup) {
        //ascending order
        if (order == 1 && aSort < bSort) {
          return -1;
        }
        //ascending order     
        else if (order == 1 && aSort > bSort) {
          return 1;
        }
        //descending order   
        else if (order == 2 && aSort > bSort) {
          return -1;
        }
        //descending order 
        else if (order == 2 && aSort < bSort) {
          return 1;
        }

      }
      return 1
    });   
    this.sortOrder = this.sortOrder == 1 ? 2 : 1;
  }

这对我有用。希望这也适合你的情况。