2

I have datatable in angular 4 application using PrimeNG and I want to sort by date named as received_at

I already created stackblitz and posted code what I have tried in this

stackbiltz link - PrimeNG datatable

below PrimeNG datatable grid

<p-dataTable [value]="interactionHistories" sortField="received_at">
  <p-column field="case_number" header="Case Number"></p-column>
  <p-column field="received_at" sortable="custom" (sortFunction)="sortByDate($event)" header="Case Date">
    <ng-template let-col let-car="rowData" let-ri="rowIndex" pTemplate="body">
      <span>{{car[col.field] | date: 'yyyy-mm-dd hh:mm:ss '}}</span>
    </ng-template>
  </p-column>
  <p-column field="status" header="Status"></p-column>
</p-dataTable>

Can anyone help me ?

Pac0
  • 21,465
  • 8
  • 65
  • 74
Chandru
  • 10,864
  • 6
  • 38
  • 53

1 Answers1

2

I had a similar problem and I solved it using a temporary array. I sorted the rows in that array, I reinitialized the original array and filled it with the temporary rows.

sortByDate(event) {
  const tmp = this.interactionHistories.sort((a: any, b: any): number => {
            if (event.field) {
                return a[event.field] > b[event.field] ? 1 : -1;
            }
        });

  if (event.order < 0) {
      tmp.reverse();
  }

  const thisRef = this;
  this.interactionHistories = [];
  tmp.forEach(function (row: any) {
      thisRef.interactionHistories.push(row);
  });

}

There might be a better solution but it works.

Working Stackblitz

Antikhippe
  • 6,316
  • 2
  • 28
  • 43