Search code examples
angularag-grid-angular

Ag-grid: how to implement filtering & sorting server side data?


I read documentation back and forth but did not find a single word about such basic feature.

Here is what I got so far:

  ngOnInit() {
    this.rowData = this.paymentMethodService.getPaymentMethods({});
  }

Getting data from Observable, note the empty {}, this is where I expect to pass filters, sorting, pagination info.

And here is a defined filter

{ headerName: 'Name', field: 'name' , sortable: true, filter: 'agTextColumnFilter' }

The filter is applied to only those rows, that were displayed initially, while I need to path its data to server.


Solution

  • You need to send to your API an information about filter and sorting. This is a rough example:

    <ag-grid-angular 
         style="width: 100%; height: 100%" 
         class="ag-theme-balham"
         [gridOptions]="gridOptions"
         [columnDefs]="yourColumns"
         (gridReady)="onGridReady($event)"
         #grid
    ></ag-grid-angular>
    

    TypeScript:

    public yourColumns: any[];
    public rowData: any[];
    public gridOptions: any;
    
    @ViewChild('grid') grid: AgGridNg2;
    
    this.yourColumns= [
          { headerName: 'One', field: 'one' },
          { headerName: 'Two', field: 'two' },
          { headerName: 'Three', field: 'three' }
        ];
    
    this.gridOptions = {
      rowSelection: 'single',
      cacheBlockSize: 100,
      maxBlocksInCache: 2,
      enableServerSideFilter: false,
      enableServerSideSorting: false,
      rowModelType: 'infinite',
      pagination: true, 
      paginationAutoPageSize: true
    };
    
     private getRowData(startRow: number, endRow: number): Observable<any[]> {
      //this code is included only for example. You need to move it to 
      //service
      let params: HttpParams = new HttpParams()
          .append('startRow', `${startRow}`)
          .append('endRow', `${endRow}`);
    
      return this.http.get(`${this.actionUrl}/GetAll`, {params: params})
          .pipe(
              map((res: any) => res.data)
          );
    }
    
    onGridReady(params: any) {
      console.log("onGridReady");
      var datasource = {
        getRows: (params: IGetRowsParams) => {
          this.getRowData(params.startRow, params.endRow)
                    .subscribe(data => params.successCallback(data));
    
        }
      };
      params.api.setDatasource(datasource);
    
    }