how to pre-set column filter in ag-grid
I think the problem is, that the grid resets the filter when new rows are loaded. There are multiple ways to approach this:
The predefined filter types have a filter parameter called newRowsAction
https://www.ag-grid.com/javascript-grid-filter-text/#paramsnewRowsAction: What to do when new rows are loaded. The default is to reset the filter. If you want to keep the filter status between row loads, then set this value to 'keep'.
This answer suggests to set the
gridOptions
propertydeltaRowDataMode=true
- You can also listen to one of the grid events that are emitted when the grid date changes and then apply the filter
https://www.ag-grid.com/javascript-grid-events/#miscellaneous:
rowDataChanged, rowDataUpdated
These should all keep the filter when the data changes but I think you still need a bit of extra logic (setting a flag) if you want the filter only on the first load.
I ended up doing this.
var FilterComponent = gridOptions.api.getFilterInstance('Status');
FilterComponent.selectNothing(); //Cleared all options
FilterComponent.selectValue('Approved') //added the option i wanted
FilterComponent.onFilterChanged();
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)
}