ag-gridag-grid-ng2

how to pre-set column filter in ag-grid


I have an Ionic/Angular app using ag-grid. I would like certain grids to have a filter automatically applied when the grid is loaded - without the user having to do anything.

I tried the following:

onGridReady(params) {
  params.api.sizeColumnsToFit();
  // get filter instance
  var filterComponent = params.api.getFilterInstance("isActive");
  // OR set filter model and update
  filterComponent.setModel({
    type: "greaterThan",
    filter: 0
  });
  filterComponent.onFilterChanged();
}

but it did nothing. Any ideas?


Solution

  • Edit: AgGrid included a onFirstDataRendered callback in version 24.0, as stated in later comments. The original answer below is now only relevant for versions which pre-date this functionality.

    onFirstDataRendered(params) {
        var filterComponent = params.api.getFilterInstance("isActive");
    
        filterComponent.setModel({
            type: "greaterThan",
            filter: 0
        });
    
        filterComponent.onFilterChanged();
    }
    

    Reproduced your problem in a couple of their example older plunks, seemed to be alleviated by adding a small delay. Just venturing a guess that maybe the DOM isn't completely ready yet, although the grid is.

    Pre-onFirstDataRendered versions:

    onGridReady(params) {
    params.api.sizeColumnsToFit();
    
    setTimeout(() => {
        var filterComponent = params.api.getFilterInstance("isActive");
        filterComponent.setModel({
          type: "greaterThan",
          filter: 0
        });
        filterComponent.onFilterChanged();
        },150)
    }