user1552545
user1552545

Reputation: 1331

How can I set default value for a filter in Ag-Grid?

I want to set a Default value to a Column filter in Ag-Grid, which is active after initialization. How can I do that?

Upvotes: 7

Views: 23343

Answers (4)

NicholaiRen
NicholaiRen

Reputation: 377

To have filters applied whenever you update the data by default. In your grid, add call backs to onRowDataUpdated

<AgGridReact                             
rowData={rowData}
columnDefs={colDefs}
onRowDataUpdated={onRowDataUpdated}/>

For the function:

function onRowDataUpdated(params) {
    params.api.setFilterModel({
        "active": {
            "values": [ "true" ],
            "filterType": "set"
        }
    });

    params.api.onFilterChanged();
}

If you don't know what to put in setFilterModel, then add a call back to onFilterChanged. After you set your filter, simply look in the log and copy the filter object from there.

function onFilterChanged(params) {
    console.log(params.api.getFilterModel());
}

<AgGridReact                             
rowData={rowData}
columnDefs={colDefs}
onFilterChanged={onFilterChanged}/>

Upvotes: 0

Martin
Martin

Reputation: 293

I had to make a couple of modifications to Jarod's answer above.

Firstly, call initialFilter() from onFirstDataRendered() instead of onGridReady()

Secondly, changed the code within initialFilter() to:

gridOptions.api.getFilterInstance('myColumn').setModel({ values: ['initial filter value'] });
gridOptions.api.onFilterChanged();

Upvotes: 0

PeterS
PeterS

Reputation: 2954

If you are using infinite model then the way to go is to set the filter model during the onGridReady function.

The setFilter takes the model that is normally provided to the getRows IDataSource call, so you can grab the object from there. For example:

  const filter = {filterItem :{
    "dateFrom": '2021-08-09',
    "dateTo": null,
    "type": "equals",
    "filterType": "date"
  }}
  gridApi.setFilterModel(filter);

The field name here is "filterItem". The grid will call the getRows with this filter and it will be shown in the display with the filter icon.

Upvotes: 1

Jarod Moser
Jarod Moser

Reputation: 7338

Looking at the example that is on the webpage under Filtering there is an input tag that is used filter with. The only change that you would need to make to this example would be to give the input an initial value with the value="" attribute.

Alternatively, you can use the onGridReady attribute of the gridOptions that you have set up. This attribute expects a function callback. so do something like:

var gridOptions{
    columnDefs: columnDefs,
    ...
    onGridReady: initialFilter,
}

function initialFilter(){
    gridOptions.api.setQuickFilter("initial filter value")
}

Upvotes: 6

Related Questions