4

Is there a way to apply a customSort to only one column with TurboTables and allow the other columns to use the default sorting?

The documentation applies the customSort to the entire table. https://www.primefaces.org/primeng/#/table/sort

Antikhippe
  • 6,316
  • 2
  • 28
  • 43
Kevin
  • 51
  • 1
  • 5

2 Answers2

0

I found a way to do this (omitting the less important parts of the code):

<p-table #tbSearch [value]="itens"...>

...
<th class="ui-sortable-column" (click)="customSort()">
    <p-sortIcon field="any.field.name.alias"></p-sortIcon> Total R$
</th>
...

Component:

import { Table } from 'primeng/table';
@ViewChild('tbSearch') tbSearch: Table;

customSort() {
    this.tbSearch.sortField = 'any.field.name.alias';
    this.tbSearch.sortOrder = -this.tbBusca.sortOrder;
    this.itens = this.itens.reverse(); // < ------ Change the original array order, for example
}
0

I have found that the simplest way to do this is to set the entire table as a custom sort and within the custom sort you can specify how to treat different columns. In my case I had a column that was based on the property of an object, so I had to sort based on that property, not based on the field.

HTML:

<p-table
    #dt
    [columns]="selectedColumns"
    [value]="filteredItems"
    [rowsPerPageOptions]="rowsPerPage"
    [loading]="loading"
    paginator="true"
    [rows]="20"
    sortMode="single"
    sortField="date"
    [resizableColumns]="true"
    [reorderableColumns]="true"
    responsive="true"
    rowExpandMode="single"
    dataKey="itemId"
    loadingIcon="fa fa-spinner"
    (sortFunction)="customSort($event)"
    [customSort]="true"
>

    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns" [pSortableColumn]="col.field" pResizableColumn pReorderableColumn>
            {{col.header}}
            <p-sortIcon [field]="col.field"></p-sortIcon>
          </th>

Typescript:

//Most of this code was derived from the primeng documentation, but I have changed it to suite my needs and company code styles. 
customSort(event: SortEvent) {
    event.data.sort((data1, data2) => {
      let value1 = data1[event.field];
      let value2 = data2[event.field];

      if (event.field === 'user') {
        value1 = (value1 as User).displayName;
        value2 = (value2 as User).displayName;
      }

      let result: number;

      if (value1 === undefined && value2 !== undefined) {
        result = -1;
      } else if (value1 !== undefined && value2 === undefined) {
        result = 1;
      } else if (value1 === undefined && value2 === undefined) {
        result = 0;
      } else if (typeof value1 === 'string' && typeof value2 === 'string') {
        result = value1.localeCompare(value2);
      } else {
        result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
      }
      return (event.order * result);
    });
  }
dmoore1181
  • 1,793
  • 1
  • 25
  • 57