You can access and set the models for filters through the grid API, or access individual filter instances directly for more control. This page details how to do both.
The filter model can be saved and restored as part of Grid State.
Get / Set All Filter Models Copy Link
It is possible to get the state of all filters using the grid API method getFilterModel(), and to set the state using setFilterModel(). These methods manage the filters states via the getModel() and setModel() methods of the individual filters.
Gets the current state of all the column filters. Used for saving filter state. |
Sets the state of all the column filters. Provide it with what you get from getFilterModel() to restore filter state.
If inferring cell data types, and row data is initially empty or yet to be set,
the filter model will be applied asynchronously after row data is added.
To always perform this synchronously, set cellDataType = false on the default column definition,
or provide cell data types for every column. |
// Gets filter model via the grid API
const model = api.getFilterModel();
// Sets the filter model via the grid API
api.setFilterModel(model);The filter model represents the state of filters for all columns and has the following structure:
// Sample filter model via getFilterModel()
{
athlete: {
filterType: 'text',
type: 'startsWith',
filter: 'mich'
},
age: {
filterType: 'number',
type: 'lessThan',
filter: 30
}
}This is useful if you want to save the global filter state and apply it at a later stage. It is also useful for server-side filtering, where you want to pass the filter state to the server.
Reset All Filters Copy Link
You can reset all filters by doing the following:
api.setFilterModel(null); Example: Get / Set All Filter Models Copy Link
The example below shows getting and setting all the filter models in action.
Save Filter Modelsaves the current filter state, which will then be displayed.Restore Saved Filter Modelrestores the saved filter state back into the grid.Set Custom Filter Modeltakes a custom hard-coded filter model and applies it to the grid.Reset Filterswill clear all active filters.Destroy Filterdestroys the filter for the Athlete column by callinggridApi.destroyFilter('athlete'). This removes any active filter from that column, and will cause the filter to be created with new initialisation values the next time it is interacted with.
(Note: the example uses the Enterprise-only Set Filter).
import {
ClientSideRowModelModule,
ColDef,
DateFilterModule,
GridApi,
GridOptions,
IDateFilterParams,
ModuleRegistry,
NumberFilterModule,
TextFilterModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ColumnsToolPanelModule,
ContextMenuModule,
FiltersToolPanelModule,
SetFilterModule,
} from "ag-grid-enterprise";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ClientSideRowModelModule,
ColumnsToolPanelModule,
FiltersToolPanelModule,
ColumnMenuModule,
ContextMenuModule,
SetFilterModule,
TextFilterModule,
NumberFilterModule,
DateFilterModule,
]);
const filterParams: IDateFilterParams = {
comparator: (filterLocalDateAtMidnight: Date, cellValue: string) => {
const dateAsString = cellValue;
if (dateAsString == null) return -1;
const dateParts = dateAsString.split("/");
const cellDate = new Date(
Number(dateParts[2]),
Number(dateParts[1]) - 1,
Number(dateParts[0]),
);
if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
return 0;
}
if (cellDate < filterLocalDateAtMidnight) {
return -1;
}
if (cellDate > filterLocalDateAtMidnight) {
return 1;
}
return 0;
},
};
const columnDefs: ColDef[] = [
{ field: "athlete", filter: "agTextColumnFilter" },
{ field: "age", filter: "agNumberColumnFilter", maxWidth: 100 },
{ field: "country" },
{ field: "year", maxWidth: 100 },
{
field: "date",
filter: "agDateColumnFilter",
filterParams: filterParams,
},
{ field: "sport" },
{ field: "gold", filter: "agNumberColumnFilter" },
{ field: "silver", filter: "agNumberColumnFilter" },
{ field: "bronze", filter: "agNumberColumnFilter" },
{ field: "total", filter: "agNumberColumnFilter" },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
columnDefs: columnDefs,
defaultColDef: {
flex: 1,
minWidth: 150,
filter: true,
},
sideBar: "filters",
onGridReady: (params) => {
params.api.getToolPanelInstance("filters")!.expandFilters();
},
};
let savedFilterModel: any = null;
function clearFilters() {
gridApi!.setFilterModel(null);
}
function saveFilterModel() {
savedFilterModel = gridApi!.getFilterModel();
const keys = Object.keys(savedFilterModel);
const savedFilters: string = keys.length > 0 ? keys.join(", ") : "(none)";
(document.querySelector("#savedFilters") as any).textContent = savedFilters;
}
function restoreFilterModel() {
gridApi!.setFilterModel(savedFilterModel);
}
function restoreFromHardCoded() {
const hardcodedFilter = {
country: {
type: "set",
values: ["Ireland", "United States"],
},
age: { type: "lessThan", filter: "30" },
athlete: { type: "startsWith", filter: "Mich" },
date: { type: "lessThan", dateFrom: "2010-01-01" },
};
gridApi!.setFilterModel(hardcodedFilter);
}
function destroyFilter() {
gridApi!.destroyFilter("athlete");
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).clearFilters = clearFilters;
(<any>window).saveFilterModel = saveFilterModel;
(<any>window).restoreFilterModel = restoreFilterModel;
(<any>window).restoreFromHardCoded = restoreFromHardCoded;
(<any>window).destroyFilter = destroyFilter;
}
.example-wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
#myGrid {
flex: 1 1 0px;
width: 100%;
}
.button-group {
padding-bottom: 1rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 13px;
}
<div class="example-wrapper">
<div>
<div class="button-group">
<button onclick="saveFilterModel()">Save Filter Model</button>
<button onclick="restoreFilterModel()">Restore Saved Filter Model</button>
<button
onclick="restoreFromHardCoded()"
title="Name = 'Mich%', Country = ['Ireland', 'United States'], Age < 30, Date < 01/01/2010"
>
Set Custom Filter Model
</button>
<button onclick="clearFilters()">Reset Filters</button>
<button onclick="destroyFilter()">Destroy Filter</button>
</div>
</div>
<div>
<div class="button-group">Saved Filters: <span id="savedFilters">(none)</span></div>
</div>
<div id="myGrid"></div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Get / Set Individual Filter Model Copy Link
It is also possible to get or set the filter model for a specific filter, including your own custom filters.
Gets the current filter model for the specified column.
Will return null if no active filter.
useUnapplied: If enableFilterHandlers = true and value is true, will return the unapplied filter model. |
Sets the filter model for the specified column.
Setting a model of null will reset the filter (make inactive).
Must wait on the response before calling api.onFilterChanged(). |
Re-running Grid Filtering Copy Link
After filters have been changed via their API, you must ensure the method gridApi.onFilterChanged() is called to tell the grid to filter the rows again. If gridApi.onFilterChanged() is not called, the grid will still show the data relevant to the filters before they were updated through the API.
// Set a filter model
await api.setColumnFilterModel('name', {
filterType: 'text',
type: 'startsWith',
filter: 'abc',
});
// Tell grid to run filter operation again
api.onFilterChanged(); Reset Individual Filters Copy Link
You can reset a filter to its original state by setting the model to null.
// Set the model to null
await api.setColumnFilterModel('name', null);
// Tell grid to run filter operation again
api.onFilterChanged(); Example: Get / Set Individual Filter Model Copy Link
The example below shows getting and setting an individual filter model in action.
Save Filter Modelsaves the Athlete filter state, which will then be displayed.Restore Saved Filter Modelrestores the saved Athlete filter state back into the grid.Set Custom Filter Modeltakes a custom hard-coded Athlete filter model and applies it to the grid.Reset Filterwill clear the Athlete filter.
import {
ClientSideRowModelModule,
ColDef,
GridApi,
GridOptions,
ICombinedSimpleModel,
IDateFilterParams,
ModuleRegistry,
NumberFilterModule,
TextFilterModel,
TextFilterModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ColumnsToolPanelModule,
ContextMenuModule,
FiltersToolPanelModule,
SetFilterModule,
} from "ag-grid-enterprise";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ClientSideRowModelModule,
ColumnsToolPanelModule,
FiltersToolPanelModule,
ColumnMenuModule,
ContextMenuModule,
SetFilterModule,
TextFilterModule,
NumberFilterModule,
]);
const filterParams: IDateFilterParams = {
comparator: (filterLocalDateAtMidnight: Date, cellValue: string) => {
const dateAsString = cellValue;
if (dateAsString == null) return -1;
const dateParts = dateAsString.split("/");
const cellDate = new Date(
Number(dateParts[2]),
Number(dateParts[1]) - 1,
Number(dateParts[0]),
);
if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
return 0;
}
if (cellDate < filterLocalDateAtMidnight) {
return -1;
}
if (cellDate > filterLocalDateAtMidnight) {
return 1;
}
return 0;
},
};
const columnDefs: ColDef[] = [
{ field: "athlete", filter: "agTextColumnFilter" },
{ field: "age", filter: "agNumberColumnFilter", maxWidth: 100 },
{ field: "country", filter: "agTextColumnFilter" },
{ field: "year", filter: "agNumberColumnFilter", maxWidth: 100 },
{ field: "sport", filter: "agTextColumnFilter" },
{ field: "gold", filter: "agNumberColumnFilter" },
{ field: "silver", filter: "agNumberColumnFilter" },
{ field: "bronze", filter: "agNumberColumnFilter" },
{ field: "total", filter: "agNumberColumnFilter" },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
columnDefs: columnDefs,
defaultColDef: {
flex: 1,
minWidth: 150,
filter: true,
},
sideBar: "filters",
onGridReady: (params) => {
params.api.getToolPanelInstance("filters")!.expandFilters(["athlete"]);
},
};
let savedFilterModel:
| TextFilterModel
| ICombinedSimpleModel<TextFilterModel>
| null = null;
function clearFilter() {
gridApi!.setColumnFilterModel("athlete", null).then(() => {
gridApi!.onFilterChanged();
});
}
function saveFilterModel() {
savedFilterModel = gridApi!.getColumnFilterModel("athlete");
const convertTextFilterModel = (model: TextFilterModel) => {
return `${(model as TextFilterModel).type} ${(model as TextFilterModel).filter}`;
};
const convertCombinedFilterModel = (
model: ICombinedSimpleModel<TextFilterModel>,
) => {
return model
.conditions!.map((condition) => convertTextFilterModel(condition))
.join(` ${model.operator} `);
};
let savedFilterString: string;
if (!savedFilterModel) {
savedFilterString = "(none)";
} else if (
(savedFilterModel as ICombinedSimpleModel<TextFilterModel>).operator
) {
savedFilterString = convertCombinedFilterModel(
savedFilterModel as ICombinedSimpleModel<TextFilterModel>,
);
} else {
savedFilterString = convertTextFilterModel(
savedFilterModel as TextFilterModel,
);
}
(document.querySelector("#savedFilters") as any).innerText =
savedFilterString;
}
function restoreFilterModel() {
gridApi!.setColumnFilterModel("athlete", savedFilterModel).then(() => {
gridApi!.onFilterChanged();
});
}
function restoreFromHardCoded() {
const hardcodedFilter = { type: "startsWith", filter: "Mich" };
gridApi!.setColumnFilterModel("athlete", hardcodedFilter).then(() => {
gridApi!.onFilterChanged();
});
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).clearFilter = clearFilter;
(<any>window).saveFilterModel = saveFilterModel;
(<any>window).restoreFilterModel = restoreFilterModel;
(<any>window).restoreFromHardCoded = restoreFromHardCoded;
}
.example-wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
#myGrid {
flex: 1 1 0px;
width: 100%;
}
.button-group {
padding-bottom: 1rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 13px;
}
<div class="example-wrapper">
<div>
<div class="button-group">
<button onclick="saveFilterModel()">Save Filter Model</button>
<button onclick="restoreFilterModel()">Restore Saved Filter Model</button>
<button
onclick="restoreFromHardCoded()"
title="Name = 'Mich%', Country = ['Ireland', 'United States'], Age < 30, Date < 01/01/2010"
>
Set Custom Filter Model
</button>
<button onclick="clearFilter()">Reset Filter</button>
</div>
</div>
<div>
<div class="button-group">Saved Filters: <span id="savedFilters">(none)</span></div>
</div>
<div id="myGrid"></div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Accessing Individual Filters Copy Link
It certain cases, it may be needed to interact directly with a specific filter. For instance, Refreshing Values on the Set Filter.
Grid-provided filters are split into two parts - the filter UI component and the filter handler (which performs the filter logic).
When enableFilterHandlers = true, Custom Filter Components are also split into two parts.
Note that the Multi Filter will only have a filter handler when enableFilterHandlers = true.
To access the filter UI component, use api.getColumnFilterInstance(colKey).
To access the filter handler, use api.getColumnFilterHandler(colKey).
Returns the filter component instance for a column.
For getting/setting models for individual column filters, use getColumnFilterModel and setColumnFilterModel instead of this.
key can be a column ID or a Column object. |
Returns the filter handler instance for a column.
Used when enableFilterHandlers = true, or when using a grid-provided filter.
If using a SimpleColumnFilter, this will be an object containing the provided doesFilterPass callback.
key can be a column ID or a Column object. |
// Get a reference to the 'name' filter UI instance
const filterInstance = await api.getColumnFilterInstance('name');If using a custom filter, any other methods you have added will also be present, allowing bespoke behaviour to be added to your filter.
Example: Accessing Individual Filters Copy Link
The example below shows how you can interact with an individual filter instance, using the Set Filter as an example.
Get Mini Filter Textwill print the text from the Set Filter's Mini Filter to the console.Save Mini Filter Textwill save the Mini Filter text.Restore Mini Filter Textwill restore the Mini Filter text from the saved state.
(Note: the example uses the Enterprise-only Set Filter).
import {
ClientSideRowModelModule,
ColDef,
GridApi,
GridOptions,
ModuleRegistry,
SetFilterUi,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ColumnsToolPanelModule,
ContextMenuModule,
FiltersToolPanelModule,
SetFilterModule,
} from "ag-grid-enterprise";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ClientSideRowModelModule,
ColumnsToolPanelModule,
FiltersToolPanelModule,
ColumnMenuModule,
ContextMenuModule,
SetFilterModule,
]);
const columnDefs: ColDef[] = [
{ field: "athlete", filter: "agSetColumnFilter" },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
columnDefs: columnDefs,
defaultColDef: {
flex: 1,
minWidth: 150,
filter: true,
},
sideBar: "filters",
onGridReady: (params) => {
params.api.getToolPanelInstance("filters")!.expandFilters();
},
};
let savedMiniFilterText: string | null = "";
function getMiniFilterText() {
gridApi!
.getColumnFilterInstance<SetFilterUi>("athlete")
.then((athleteFilter) => {
console.log(athleteFilter!.getMiniFilter());
});
}
function saveMiniFilterText() {
gridApi!
.getColumnFilterInstance<SetFilterUi>("athlete")
.then((athleteFilter) => {
savedMiniFilterText = athleteFilter!.getMiniFilter();
});
}
function restoreMiniFilterText() {
gridApi!
.getColumnFilterInstance<SetFilterUi>("athlete")
.then((athleteFilter) => {
athleteFilter!.setMiniFilter(savedMiniFilterText);
});
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).getMiniFilterText = getMiniFilterText;
(<any>window).saveMiniFilterText = saveMiniFilterText;
(<any>window).restoreMiniFilterText = restoreMiniFilterText;
}
.example-wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
#myGrid {
flex: 1 1 0px;
width: 100%;
}
.example-header {
padding-bottom: 1rem;
}
<div class="example-wrapper">
<div class="example-header">
<button onclick="getMiniFilterText()">Get Mini Filter Text</button>
<button onclick="saveMiniFilterText()">Save Mini Filter Text</button>
<button onclick="restoreMiniFilterText()">Restore Mini Filter Text</button>
</div>
<div id="myGrid"></div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Read-only Filter UI Copy Link
Sometimes it maybe useful to strictly control the filters used by the grid via API, whilst still exposing filter settings in-use to users. The readOnly filter parameter changes the behaviour of all provided column filters so their UI is read-only. In this mode, API filter changes are still honoured and reflected in the UI:
const gridOptions = {
columnDefs: [
{
field: 'age',
filter: true,
filterParams: {
readOnly: true
}
}
],
// other grid options ...
}The following example demonstrates all of the Provided Filters with readOnly: true enabled:
- Simple Filters have a read-only display with no buttons; if there is no 2nd condition set then the join operator and 2nd condition are hidden:
athletecolumn demonstrates Text Filter.ageandyearcolumns demonstrate Number Filter.datecolumn demonstrates Date Filter.
- Set Filter allows Mini Filter searching of values, but value inclusion/exclusion cannot be toggled; buttons are also hidden, and pressing enter in the Mini Filter input has no effect:
country,gold,silverandbronzecolumns demonstrate Set Filter.
- Multi Filter has no direct behaviour change, sub-filters need to be individually made read-only.
readOnly: trueis needed to affect any associated Floating Filters.sportcolumn demonstrates Multi Filter.
- Floating Filters are enabled and inherit
readOnly: truefrom their parent, disabling any UI input. - Buttons above the grid provide API interactions to configure the filters.
Print Countrybutton prints the country model to the developer console.
import {
ClientSideRowModelModule,
ColDef,
DateFilterModule,
FilterWrapperParams,
GridApi,
GridOptions,
IMultiFilterParams,
ISetFilterParams,
ITextFilterParams,
ModuleRegistry,
NumberFilterModule,
SetFilterHandler,
TextFilterModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ColumnsToolPanelModule,
ContextMenuModule,
MultiFilterModule,
SetFilterModule,
} from "ag-grid-enterprise";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ClientSideRowModelModule,
ColumnsToolPanelModule,
ColumnMenuModule,
ContextMenuModule,
MultiFilterModule,
SetFilterModule,
TextFilterModule,
NumberFilterModule,
DateFilterModule,
]);
const defaultFilterParams: FilterWrapperParams = { readOnly: true };
const columnDefs: ColDef[] = [
{
field: "athlete",
},
{
field: "age",
},
{
field: "country",
filter: "agSetColumnFilter",
},
{
field: "year",
maxWidth: 120,
},
{
field: "date",
minWidth: 215,
suppressHeaderMenuButton: true,
},
{
field: "sport",
suppressHeaderMenuButton: true,
filter: "agMultiColumnFilter",
filterParams: {
filters: [
{
filter: "agTextColumnFilter",
filterParams: { readOnly: true } as ITextFilterParams,
},
{
filter: "agSetColumnFilter",
filterParams: { readOnly: true } as ISetFilterParams,
},
],
readOnly: true,
} as IMultiFilterParams,
},
{
field: "gold",
filter: "agSetColumnFilter",
},
{
field: "silver",
filter: "agSetColumnFilter",
},
{
field: "bronze",
filter: "agSetColumnFilter",
},
{ field: "total", filter: false },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
columnDefs: columnDefs,
defaultColDef: {
flex: 1,
minWidth: 150,
filter: true,
floatingFilter: true,
filterParams: defaultFilterParams,
},
suppressSetFilterByDefault: true,
};
function irelandAndUk() {
gridApi!
.setColumnFilterModel("country", { values: ["Ireland", "Great Britain"] })
.then(() => {
gridApi!.onFilterChanged();
});
}
function clearCountryFilter() {
gridApi!.setColumnFilterModel("country", null).then(() => {
gridApi!.onFilterChanged();
});
}
function destroyCountryFilter() {
gridApi!.destroyFilter("country");
}
function endingStan() {
const countriesEndingWithStan = gridApi!
.getColumnFilterHandler<SetFilterHandler>("country")!
.getFilterKeys()
.filter(function (value: any) {
return value.indexOf("stan") === value.length - 4;
});
gridApi!
.setColumnFilterModel("country", { values: countriesEndingWithStan })
.then(() => {
gridApi!.onFilterChanged();
});
}
function printCountryModel() {
const model = gridApi!.getColumnFilterModel("country");
if (model) {
console.log("Country model is: " + JSON.stringify(model));
} else {
console.log("Country model filter is not active");
}
}
function sportStartsWithS() {
gridApi!
.setColumnFilterModel("sport", {
filterModels: [
{
type: "startsWith",
filter: "s",
},
],
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function sportEndsWithG() {
gridApi!
.setColumnFilterModel("sport", {
filterModels: [
{
type: "endsWith",
filter: "g",
},
],
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function sportsCombined() {
gridApi!
.setColumnFilterModel("sport", {
filterModels: [
{
conditions: [
{
type: "endsWith",
filter: "g",
},
{
type: "startsWith",
filter: "s",
},
],
operator: "AND",
},
],
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function ageBelow25() {
gridApi!
.setColumnFilterModel("age", {
type: "lessThan",
filter: 25,
filterTo: null,
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function ageAbove30() {
gridApi!
.setColumnFilterModel("age", {
type: "greaterThan",
filter: 30,
filterTo: null,
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function ageBelow25OrAbove30() {
gridApi!
.setColumnFilterModel("age", {
conditions: [
{
type: "greaterThan",
filter: 30,
filterTo: null,
},
{
type: "lessThan",
filter: 25,
filterTo: null,
},
],
operator: "OR",
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function ageBetween25And30() {
gridApi!
.setColumnFilterModel("age", {
type: "inRange",
filter: 25,
filterTo: 30,
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function clearAgeFilter() {
gridApi!.setColumnFilterModel("age", null).then(() => {
gridApi!.onFilterChanged();
});
}
function after2010() {
gridApi!
.setColumnFilterModel("date", {
type: "greaterThan",
dateFrom: "2010-01-01",
dateTo: null,
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function before2012() {
gridApi!
.setColumnFilterModel("date", {
type: "lessThan",
dateFrom: "2012-01-01",
dateTo: null,
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function dateCombined() {
gridApi!
.setColumnFilterModel("date", {
conditions: [
{
type: "lessThan",
dateFrom: "2012-01-01",
dateTo: null,
},
{
type: "greaterThan",
dateFrom: "2010-01-01",
dateTo: null,
},
],
operator: "OR",
})
.then(() => {
gridApi!.onFilterChanged();
});
}
function clearDateFilter() {
gridApi!.setColumnFilterModel("date", null).then(() => {
gridApi!.onFilterChanged();
});
}
function clearSportFilter() {
gridApi!.setColumnFilterModel("sport", null).then(() => {
gridApi!.onFilterChanged();
});
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) =>
gridApi!.setGridOption(
"rowData",
data.map((rowData) => {
const dateParts = rowData.date.split("/");
return {
...rowData,
date: `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`,
};
}),
),
);
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).irelandAndUk = irelandAndUk;
(<any>window).clearCountryFilter = clearCountryFilter;
(<any>window).destroyCountryFilter = destroyCountryFilter;
(<any>window).endingStan = endingStan;
(<any>window).printCountryModel = printCountryModel;
(<any>window).sportStartsWithS = sportStartsWithS;
(<any>window).sportEndsWithG = sportEndsWithG;
(<any>window).sportsCombined = sportsCombined;
(<any>window).ageBelow25 = ageBelow25;
(<any>window).ageAbove30 = ageAbove30;
(<any>window).ageBelow25OrAbove30 = ageBelow25OrAbove30;
(<any>window).ageBetween25And30 = ageBetween25And30;
(<any>window).clearAgeFilter = clearAgeFilter;
(<any>window).after2010 = after2010;
(<any>window).before2012 = before2012;
(<any>window).dateCombined = dateCombined;
(<any>window).clearDateFilter = clearDateFilter;
(<any>window).clearSportFilter = clearSportFilter;
}
.example-wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
#myGrid {
flex: 1 1 0px;
width: 100%;
}
.example-header {
padding-bottom: 1rem;
}
.button-group {
padding-bottom: 4px;
display: block;
}
<div class="example-wrapper">
<div class="example-header">
<span class="button-group">
<button onclick="irelandAndUk()">Ireland & UK</button>
<button onclick="endingStan()">Countries Ending 'stan'</button>
<button onclick="printCountryModel()">Print Country</button>
<button onclick="clearCountryFilter()">Clear Country</button>
<button onclick="destroyCountryFilter()">Destroy Country</button>
</span>
<span class="button-group">
<button onclick="ageBelow25()">Age Below 25</button>
<button onclick="ageAbove30()">Age Above 30</button>
<button onclick="ageBelow25OrAbove30()">Age Below 25 or Above 30</button>
<button onclick="ageBetween25And30()">Age Between 25 and 30</button>
<button onclick="clearAgeFilter()">Clear Age Filter</button>
</span>
<span class="button-group">
<button onclick="after2010()">Date after 01/01/2010</button>
<button onclick="before2012()">Date before 01/01/2012</button>
<button onclick="dateCombined()">Date combined</button>
<button onclick="clearDateFilter()">Clear Date Filter</button>
</span>
<span class="button-group">
<button onclick="sportStartsWithS()">Sport starts with S</button>
<button onclick="sportEndsWithG()">Sport ends with G</button>
<button onclick="sportsCombined()">Sport starts with S and ends with G</button>
<button onclick="clearSportFilter()">Clear Sport Filter</button>
</span>
</div>
<div id="myGrid" style="height: 100%"></div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Launching Filters Copy Link
How filters are launched can be customised (unless grid option columnMenu = 'legacy').
colDef.suppressHeaderFilterButton = true can be used to disable the button in the header that opens the filter.
The filter can also be launched via api.showColumnFilter(columnKey) and hidden via api.hideColumnFilter().
The following example demonstrates launching the filter:
- The Athlete column has a filter button in the header to launch the filter.
- The Age column has a floating filter, so the header button is automatically hidden.
- The Country column has the filter button hidden via
colDef.suppressHeaderFilterButton. The filter can still be opened via the API by clicking theOpen Country Filterbutton. - The Year column has a floating filter and the header button is also suppressed, so has a slightly different display style when the filter is active.
import {
ClientSideRowModelModule,
ColDef,
GridApi,
GridOptions,
ModuleRegistry,
NumberFilterModule,
TextFilterModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
TextFilterModule,
NumberFilterModule,
ClientSideRowModelModule,
]);
const columnDefs: ColDef[] = [
{ field: "athlete" },
{ field: "age", floatingFilter: true },
{ field: "country", suppressHeaderFilterButton: true },
{
field: "year",
maxWidth: 120,
floatingFilter: true,
suppressHeaderFilterButton: true,
},
{ field: "sport" },
{ field: "gold" },
{ field: "silver" },
{ field: "bronze" },
{ field: "total", filter: false },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
columnDefs: columnDefs,
defaultColDef: {
flex: 1,
minWidth: 150,
filter: true,
},
};
function openCountryFilter() {
gridApi.showColumnFilter("country");
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).openCountryFilter = openCountryFilter;
}
.example-wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
#myGrid {
flex: 1 1 0px;
width: 100%;
}
.button-group {
padding-bottom: 1rem;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 13px;
}
<div class="example-wrapper">
<div>
<div class="button-group">
<button onclick="openCountryFilter()">Open Country Filter</button>
</div>
</div>
<div id="myGrid"></div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Filter Events Copy Link
Filtering causes the following events to be emitted:
Filter has been opened. |
Filter has been modified and applied. |
Filter was modified but not applied (when using enableFilterHandlers = false). Used when filters have 'Apply' buttons. |
Filter UI was modified (when using enableFilterHandlers = true). |
Floating filter UI modified (when using enableFilterHandlers = true). |