In this video, we'll use the filter API in conjunction with the grid API to programatically set and modify filters.
We're going to create a button that does the following:
- Sets the amount filter to "less than 100"
- Sets the last name filter to "contains 'Mo'"
- Sorts the grid by amount descending
First, let's add a button between the quick filter input and the AgGridReact
Component:
// src/App.js
<button type="button" onClick={this.moFilter}>
Mo Filter
</button>
Then, we'll create the moFilter
function we're using in our onClick
event handler. This function needs to:
- Get the instances of the filters,
- Set each filter model,
- Sort the grid by amount descending, and
- Tell ag-Grid to update the filters.
Here's the finished function:
// src/App.js
moFilter = () => {
// get the instance of the filter on each column
const lastNameFilter = this.gridApi.getFilterInstance("lastName");
const amountFilter = this.gridApi.getFilterInstance("amount");
// set the filter model
lastNameFilter.setModel({
type: "contains",
filter: "Mo"
});
amountFilter.setModel({
type: "lessThan",
filter: 100
});
// sort the grid
this.gridApi.setSortModel([{ colId: "amount", sort: "desc" }]);
// tell ag-Grid to update the filters
this.gridApi.onFilterChanged();
};
If you run npm start
and navigate to localhost:3000, you should be able to click the "Mo Filter" button and watch in amazement as two filters are adjusted and the grid is sorted instantaneously! Pretty cool, right?
Being able to programatically update filters is insanely powerful. I hope you'll check out the docs and explore.
For our last filter feature, let's learn about set filters in the next video.