Search code examples
angularsortingprimeng

PrimeNg Datatable Custom Sorting repeating itself


I have a datatable in Angular 2 app where I want to custom sort a column.

<p-column field="eligible" header="Eligible" sortable="custom" (sortFunction)="sortColumn($event)"></p-column>

In my component file, I'm making an API call to get the sorted results from the backend based on some logic.

sortColumn(colName: any) {
  let columnName = undefined !== colName.field ? colName.field : colName;
  let sortObject: any = {};
  if (this.sortedColumn === columnName) {
   if (!this.sortAsc) {
     this.sortAsc = true;
     sortObject[columnName] = 'DESC';
   } else {
    this.sortAsc = false;
    sortObject[columnName] = 'ASC';
 }
 } else {
  this.sortedColumn = columnName;
  this.sortAsc = false;
  sortObject[columnName] = 'ASC';
 }
this.getData(sortObject);
}

This API in return gets the whole data back and reorders the view. Now what's happening here is that this method sortColumn() keeps getting called repeatedly.

Can anyone please help me understand what might be causing this issue and how to resolve it?


Solution

  • You can to try event onSort of datatable

    <p-dataTable [value]="data" (onSort)="sortColumn($event)>
      <p-column field="vin" header="Vin" ></p-column>
    
      <p-column field="eligible"  header="Eligible" [sortable]="true"></p-column>    
    
      <p-column field="year" header="Year"></p-column>
      <p-column field="color" header="Color" ></p-column>
    </p-dataTable>
    

    this event has event.field: Field name of the sorted column and and event.order (1 o -1) event.order. This event is invoked only when click in sort column.

    I hope that it help you.