Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 261
Abhishek Avatar asked Jun 25 '17 15:06

Abhishek


2 Answers

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.

like image 191
alehn96 Avatar answered Oct 14 '22 14:10

alehn96


I got repetitive http calling problem for using both onSort and sortFunction in p-table in Prime ng. Problem was solved using [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
   }
like image 42
Jasmin Akther Suma Avatar answered Oct 14 '22 15:10

Jasmin Akther Suma