Primeng Lazy load triggering multiple times while update the sortField and sortOrder?

Viewed 742

I have implemented lazyload on my primeng-table,

<p-table #dataTable [columns]="tableHeader" [value]="tableData" [rows]="10" [paginator]="true"
[rowsPerPageOptions]="rowsPerPage" [totalRecords]="totalRecords" [sortField]="sortField" [sortOrder]="sortType"
rowHover="true" [lazy]=true (onLazyLoad)="loadLazy($event)">

And user can change the column by value selection (it is handled by API call). The problem is, If I update the sortField and sortOrder API is triggering two times.

    this.dataTable.sortField = obj.sortField;
    this.dataTable.sortOrder = obj.sortType;
    this.loadTableData(); // this method is triggered to fetch the API data. 

With the above code, I don't want to trigger the loadLazy method for multiple times.

So, I have tried the following code,

    this.dataTable.lazy = false;
    this.dataTable.sortField = obj.sortField;
    this.dataTable.sortOrder = obj.sortType;
    this.loadTableData(); // this method is triggered to fetch the API data. 
    this.dataTable.lazy = true;

But if I set the lazy to false and true, the pagination is not showing up.? could you guys suggest me where I am making the problem.?

1 Answers

my guess is that [sortField]="sortField" [sortOrder]="sortType" is not intended to work with lazy mode, because indeed it does trigger the onLazyLoad event !

So If I had to come with a solution, I'd try to go with the event that can handle all the filtering, sorting and page parameters at the same time. This means getting the ViewChild of the p-table and trigger the onLazyLoad event.

When you read this : https://github.com/primefaces/primeng/blob/master/src/app/components/table/table.ts

You see that you can send the whole set of parameters. Anyway, I'll try that myself :) Cheers.

-------------- EDIT ---------------

This actually works as expected, this is pretty nice, so you can retreive your Table like this :

import { Table } from 'primeng/table';

@ViewChild(Table) table!: Table;

And then you emit the event, and it will be catched by your own callback method, like so :

somemethod(): void {
    this.table.onLazyLoad.emit({
      sortField: 'designation',
      sortOrder: -1
    })
  }

But beware that omitted parameters are not automatically retreived from the actual state of the table, you need to value them.

Related