mkHun
mkHun

Reputation: 5927

How to make p-table reset with default sorting in primeng?

I am loading the data from API. The data is huge so I am using the lazyloading.

On the page load I am sorting the table by giving the input in the HTML template like below, it is working fine

<p-table [value]="data" [rows]="10" sortField="id" [sortOrder]="-1" 
  [lazy]="true" (onLazyLoad)="loadLazy($event)">

But my page has the reset button also, So if the user clicks the button I am trying to reset it default.

So in my component code I used the below code

this.dataTable.reset();

The problem is I am trying to sort the table. So I used the following code,

this.dataTable.reset();
this.dataTable.sortField = 'id';
this.dataTable.sortOrder = 1;

using the above code the table gets sorted and the problem is API is calling 3 times. So I am trying to implement the sort on the table reset. So I tried the below code,

this.dataTable.reset({'sortField':'id',sortOrder: 1});

But I am getting the error. How can I do it?

Upvotes: 1

Views: 7342

Answers (2)

Binary Alchemist
Binary Alchemist

Reputation: 1620

I tried the answer provided by @tano, but the default sort ('id') was not being maintained.

this.dataTable.lazy = false;
this.dataTable.reset();
this.dataTable._sortOrder = 1;
this.dataTable._sortField = 'id';
this.dataTable.lazy = true;
// calls the endpoint
this.dataTable.sortSingle();

Upvotes: 1

tano
tano

Reputation: 2817

The problem is that the sortField and sortOrder are setters and trigger loading. you can hack it for example this way.

this.dataTable.lazy = false;
this.dataTable.reset();
this.dataTable._sortOrder = 1;
this.dataTable.lazy = true;
// calls the endpoint
this.dataTable.sortField = 'id';

But of course your onLazyLoad method can check if $event.sortField is set or not and return.

I'd choose the 2nd option since that is not a hack just a validation. The point is that the sortField must be set at last just like in you example.

Upvotes: 5

Related Questions