Search code examples
angularangular-materialag-gridpollingag-grid-angular

How to keep filter intact during polling in angular?


<div class="device-view">
  <mat-toolbar>
    <span class="device-list-label">Device List</span>
  </mat-toolbar>
  <div class="device-list">
    <ag-grid-angular
      style="width: 100%; height: 100%;"
      class="ag-theme-material"
      (gridReady)="onGridReady($event)"
      [suppressDragLeaveHidesColumns]="true"
      [frameworkComponents]="frameworkComponents"
      (columnResized)="onColumnResized($event)"
      [rowData]="rowData"
      [columnDefs]="columnDefs"
      [defaultColDef]="defaultColumnDefs"
      [enableSorting]="true"
      [enableFilter]="true"
      [animateRows]="true"
      [rowHeight]="32"
      [headerHeight]="35"
      [suppressRowClickSelection]="true"
      [rowSelection]="rowSelection"
      (selectionChanged)="onSelectionChanged()"
      (filterChanged)="onFilterChanged($event)"
      [modules]="modules"
    </ag-grid-angular>
  </div>
</div>

This is my code for polling. I am calling update method in ngOnit().

update(){
this.timeInterval = interval(10000)
  .pipe(
    startWith(0),
    switchMap(() => this.deviceService.getDeviceList())
  )
  .pipe(
    takeUntil(this.deviceService.flag$),
    repeatWhen(() => this.deviceService.flag$)
  )
  .subscribe((success: any) => {
    this.gridApi?.setRowData(this.updatedData);
    this.restoreFilterModel(); 
    this.updatedData = success;
    console.log("test")
  }, retry(2));
}

These are the methods to restore the state of the filter and apply the filter model whenevr new data comes.

saveFilterModel() {
    this.savedFilterModel1 = this.gridApi.getFilterModel();
    const keys = Object.keys(this.savedFilterModel1);
    const savedFilters = keys.length > 0 ? keys.join(', ') : '(none)';
    document.querySelector('#savedFilters').innerHTML = savedFilters;
}

onFilterChanged(event: any) {
  this.savedFilterModel1 = this.gridApi.getFilterModel();
  const keys = Object.keys(this.savedFilterModel1);
  const savedFilters = keys.length > 0 ? keys.join(', ') : '(none)';

}

restoreFilterModel() {
  if (this.gridApi) {
    this.gridApi.setFilterModel(this.savedFilterModel1);
    this.gridApi.refreshClientSideRowModel('filter');
  }
}

The issue is there is a minor flicker, when data comes the screen first shows the entire data and then filter the data. How do i avoid the flicker. What changes do i need to make in the code?


Solution

  • You're saving and restoring the filters manually, you don't need to do that. What you're missing is the following code for your column definition:

    filterParams: {
        newRowsAction: 'keep'
    }
    

    So add the above code into your defaultColumnDefs so it gets applied to every column.

    From documentation:

    It is recommended that newRowsAction='keep' is set on the filter params to keep existing filter selections when new rows are added

    Demo