PrimeNg Datatable Custom Sorting repeats

I have a datatable in Angular 2 app where I want to customize column sorting.

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

      

In my component file, I am making an API call to get 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 turn returns all data and reorders the view. Now, what's going on here is this sortColumn () method keeps getting calls again.

Can anyone help me understand what might be causing this problem and how to solve it?

+6


source to share


2 answers


You can try onSort event 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: sorted column field name and event.order (1 o -1) event.order. This event is only fired when a click is made in the sort column.

I hope this helps you.

+5


source


I got a repetitive issue of calling http to use both onSort and sortFunction on a p-table in Prime ng. The problem was solved with [lazy] = "true", (onLazyLoad) = "customSort ($ event)" in p-table tag in angular8.

HTML:

<p-table [loading]="isLoading"
         [value]="listProjectClone"
         [scrollable]="true"
         sortMode="single"
         styleClass="custom-table borderless" [lazy]="true" 
         (onLazyLoad)="customSort($event)">

      



TS file code:

import { LazyLoadEvent } from 'primeng/api';

customSort(event: LazyLoadEvent) {   
    this.sortBy = event.sortField;
    this.sortOrderBy = event.sortOrder == 1 ? 'ASC' : 'DESC';
    //http call to server
   }

      

0


source







All Articles