Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically trigger refresh primeNG datatable when a button is clicked

I have a refresh button that is outside the primeNG datatable. How do I programmatically trigger to refresh the datatable?

something like this:

<div class="pull-right">
  <button
    id="FilterBtnId"
    (click)="???">
  </button>
                </div>
<p-dataTable
   #datatable
   [value]="datasource"
   [(selection)]="jobs"
   [totalRecords]="totalRecords"
   selectionMode="multiple"
   resizableColumns="true"
   [pageLinks]="10"
   [rows]="10"
   [rowsPerPageOptions]="[10, 25, 50, 100]"
   [paginator]="true"
   [responsive]="true"
   [lazy]="true"
   (onLazyLoad)="getNewDatasource($event)"
   (onRowSelect)="onRowSelect($event)"
   >
     <p-column [style]="{'width':'40px'}" selectionMode="multiple"></p-column>
     <p-column *ngFor="let col of dt.colDefs" [field]="col.field" [header]="col.headerName" [sortable]="true">
     </p-column>
</p-dataTable>
like image 645
kimondoe Avatar asked Oct 17 '16 00:10

kimondoe


3 Answers

The Angular form guide contains a small trick that could be used as a workaround, it consists on recreating the dom by adding *ngIf to the element to control its visibility

visible: boolean = true;
updateVisibility(): void {
  this.visible = false;
  setTimeout(() => this.visible = true, 0);
}

<button (click)="updateVisibility()">
<p-dataTable *ngIf="visible">
like image 174
Mauricio Poppe Avatar answered Oct 14 '22 19:10

Mauricio Poppe


We can have small trick to update the dataTable here: we can recreating the div by adding *ngIf to the element to control its visibility by this it will update dataTable also.

    visible: boolean = true;
    updateVisibility(): void {
      this.visible = false;
    }
    <button (click)="updateVisibility()">

    <div *ngIf="visible">
        <p-dataTable></p-dataTable>
    </div>
like image 5
Nitin Jangid Avatar answered Oct 14 '22 20:10

Nitin Jangid


If the table is in Lazy mode (loads data dynamically from a server with pagination and so on...) a better way to do this (preserving the page number, sorting, filter and so on) is listed here.

The solution is:

On your component template:

<p-table [value]="yourData" [lazy]="true" (onLazyLoad)="loadUserData($event)" ...

On your component code:

private lastTableLazyLoadEvent: LazyLoadEvent;

loadUserData(event: LazyLoadEvent): void {
    this.lastTableLazyLoadEvent = event;
    // Lots of beautifull data loading code here 
    // (like calling a server trough a service and so on)...
}

...

And when you want to reload the table (e.g. when you insert or delete an item from the server):

this.loadUserData(this.lastTableLazyLoadEvent);
like image 5
Iogui Avatar answered Oct 14 '22 21:10

Iogui