Filtering

You have two options for filtering, one is use one of the default built-in filters (easy but restricted to what's provided), or bake your own custom filters (no restrictions, build what you want, but takes more time).

This page discusses filtering outside of the context of paging. To see how to implement server side filtering, see the sections pagination and virtual paging

Enable Filtering

Enable filtering by setting grid property enableFilter=true. This turns on filtering on all columns. To turn off filtering for particular columns, set suppressFilter=true on the individual column definition.

When a filter is active on a column, the filter icon appears before the column name in the header.

Default Built-In Filters

The following filter options can be set for a column definition:

Filter Description
number A number comparison filter. Functionality for matching on {equals, less than, greater than}.
text A string comparison filter. Functionality for matching on {contains, starts with, ends with, equals}.
date A date comparison filter. Functionality for matching on {equals, not equals, less than, greater than, in range}.
set A set filter, influenced by how filters work in Microsoft Excel. This is an ag-Grid-Enterprise feature and explained further here

If no filter type is specified, the default 'text' filter is used (unless you are using ag-Grid-Enterprise, in which case the 'set' filter is the default).

Filter Parameters

As well as specifying the filter type, you can also provide setup parameters for the filters by setting colDef.filterParams. The available parameters are specific to the filter type. What follows is an example of setting 'apply=true' and 'newRowsAction=keep' on a text filter:

columnDefinition = {
    headerName: "Athlete",
    field: "athlete",
    filter: 'text',
    filterParams: {apply: true, newRowsAction: 'keep'}
}

Text, Number and Date Filter Parameters

The filter parameters for text, date and number filter have the following meaning:

  • newRowsAction: 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'.
  • apply: Set to true to include an 'Apply' button with the filter and not filter automatically as the selection changes.

The date filter has an additional property to specify how the filter date should be compared with the data in your cell:

  • comparator: A callback to specify how the current row's value compares to the filter. This is explained below in the section Date Filter Comparator.

Built In Filters Example

The example below demonstrates:

  • Three filter types text filter, number filter and date filter.
  • Quick filter
  • using the ag-header-cell-filtered class, which is applied to the header cell when the header is filtered. By default, no style is applied to this class, the example shows applying a different color background to this style.
  • 'suppressFilter' is set on Total to hide the filter on this column

Date Filter

The date filter allows filtering by dates. It is more complex than the text and number filters as it allows custom comparators and also custom date pickers.

Date Filter Comparator

Dates can be represented in your data in many ways e.g. as a JavaScript Date object, or as a string in the format eg "26-MAR-2020" or something else different. How you represent dates will be particular to your application. If you are filtering JavaScript date objects the filter will work automatically, but if you are representing your date in any other format you will have to provide your own comparator callback.

The comparator callback takes two parameters. The first parameter is a Javascript date object with the local date at midnight selected in the filter. The second parameter is the current value of the cell being evaluated. The callback must return:

  • Any number < 0 if the cell value is less than the filter date
  • 0 if the dates are the same
  • Any number > 0 if the cell value is greater than the filter date
This pattern is intended to be similar to the JavaScript compareTo(a,b) function.

Below is an example of using a date filter with a comparator.

colDef = {
    ...
    // specify we want to use the date filter
    filter: 'date',

    // add extra parameters for the date filter
    filterParams:{

        // provide comparator function
        comparator: function (filterLocalDateAtMidnight, cellValue) {

            // In the example application, dates are stored as dd/mm/yyyy
            // We create a Date object for comparison against the filter date
            var dateParts  = cellValue.split("/");
            var day = Number(dateParts[2]);
            var month = Number(dateParts[1]) - 1;
            var year = Number(dateParts[0]);
            var cellDate = new Date(day, month, year);

            // Now that both parameters are Date objects, we can compare
            if (cellDate < filterLocalDateAtMidnight) {
                return -1;
            } else if (cellDate > filterLocalDateAtMidnight) {
                return 1;
            } else {
                return 0;
            }
        }
    }
}

Custom Date Component

It is possible to specify your own component to be used as a date picker. By default the grid will us the browser provided date picker for Chrome (as we think it's nice), but for all other browser it will just provide a simple text field. It is assumed that you will have a chosen date picker for your application. In this instance you can provide your chosen date picker to ag-Grid. This is done by providing a custom Date Component via the grid property dateComponent as follows:

gridOptions: {
    ...
    // Here is where we specify the component to be used as the date picket widget
    dateComponent: MyDateEditor
}},

The interface for dateComponent is similar to that of a cellRenderer and is as follows:

interface IDateComp {
    // Callback received to signal the creation of this cellEditorRenderer,
    // placeholder to create the necessary logic to setup the component,
    // like initialising the gui, or any other part of your component
    init?(params: IDateParams): void;

    // Return the DOM element of your editor, this is what the grid puts into the DOM
    getGui(): HTMLElement;

    // Gets called once by grid after editing is finished.
    // If your editor needs to do any cleanup, do it here
    destroy?(): void;

    // Returns the current date represented by this editor
    getDate(): Date;

    // Sets the date represented by this component
    setDate(date:Date): void;

    // A hook to perform any necessary operation just after the
    // gui for this component has been renderer in the screen
    afterGuiAttached?(params?: IAfterGuiAttachedParams): void;
}

The params object for the DateComponent has the following signature:

export interface IDateCompParams {
    // Method for component to tell ag-Grid that the date has changed
    onDateChanged:()=>void
}

The onDateChanged method is used to tell ag-Grid the date selection has changed. You are responsible to hook this method inside your date component so that every time that the date changes inside the component, this method is called, so that ag-Grid can proceed with the filtering.

See below an example of a custom JQuery date picker.

Apply Function

If you want the user to hit an 'Apply' button before the filter is actioned, add apply=true to the filter parameters. The example below shows this in action for the first three columns.

This is handy if the filtering operation is taking a long time (usually it doesn't), or if doing server side filtering (thus preventing unnecessary calls to the server).

The example below also demonstrates the filter hook callbacks (see your browser dev console).

  • onFilterModified gets called when the filter changes regardless of the apply button.
  • onBeforeFilterChanged gets called before a new filter is applied.
  • onAfterFilterChanged gets called after a new filter is applied.
  • Filtering Animation

    To enable animation of the rows after filtering, set grid property animateRows=true.

    External Filtering

    It is common for you to want to have widgets on the top of your grid that influence the grids filtering. External filtering allows you to mix your own 'outside of the grid' filtering with the grids filtering.

    The example below shows external filters in action. There are two methods on gridOptions you need to implement: isExternalFilterPresent() and doesExternalFilterPass(node).

    • isExternalFilterPresent is called exactly once every time the grid senses a filter change. It should return true if external filtering is active, otherwise false. If you return true, then doesExternalFilterPass() will be called while filtering, otherwise doesExternalFilterPass() will not be called.
    • doesExternalFilterPass is called once for each row node in the grid. If you return false, the node will be excluded from the final set.

    If the external filter changes, then you need to call api.onFilterChanged() to tell the grid

    The example below shows the external filters in action.

    Quick Filter

    In addition to the column specific filtering, a 'quick filter' (influenced by how filtering is done in Google GMail) can also be applied. Set the quick filter text into the grid options and tell the grid, via the API, to filter the data (which will include the new quick filter).

    How it Works

    Each node gets a quick filter text attached to it by concatenating all the values for each column. For example, a {Employee Name, Job} table could have a row with quick filter text of 'Niall Crosby_Coffee Maker'. The grid then does a simple string search, so if you search for 'Niall', it will find our example text. Joining all the columns values into one string gives a huge performance boost. The values are joined after the quick filter is requested for the first time and stored in the rowNode - the original data that you provide is not changed.

    Overriding the Quick Filter Value

    If your data contains complex objects, then the quick filter will end up with [object,object] inside it instead of searchable string values. Or maybe you want to format string values for searching (eg take out accent characters, or take out commas from numbers). If you want to do this, then provide a getQuickFilterText to the column definition, eg:

    colDef = {
        headerName: "D", field: "d",
        getQuickFilterText: function(params) {
            return params.value.name;
        }
    }
    Params contains {value, node, data, column, colDef}.

    You only need to override the quick filter value if you have a problem. If you don't have a quick filter problem, you don't need to use it, quick filter will work 'out of the box' in most cases.

    Reset Quick Filters

    Quick filters can be reset in any of the following ways:

    • Each rowNode has a resetQuickFilterAggregateText method on it - call this to reset the quick filter
    • rowNode.setDataValue(colKey, newValue) will also reset the quick filter
    • Lastly, if using the grid editing features, when you update a cell, the quick filter will get reset.

    Quick Filter Example

    The example below shows the quick filter working on different data types. Each column demonstrates something different as follows:

    • A - Simple column, nothing complex.
    • B - Complex object with 'dot' in field, quick filter works fine.
    • C - Complex object and value getter used, again quick filter works fine.
    • D - Complex object, quick filter would call 'toString' on the complex object, so getQuickFilterText is provided.
    • E - Complex object, not getQuickFilterText provided, so the quick filter text ends up with '[object,object]' for this column.
    To see the quick filter text attached to each node, click 'Print Quick Filter Texts' button after you execute the quick filter at least one. You will notice the quick filter text is correct for each column except E (which would be fixed by adding an appropriate getQuickFilterText method like D does).

    Accessing Filter Component Instances

    It is possible to access the filter components directly if you want to interact with the specific filter. This also works for your own custom filters, where you can get a reference to the underlying filtering instance (ie what was created after ag-Grid called 'new' on your filter). You get a reference to the filter instance by calling api.getFilterInstance(colKey).

    // Get a reference to the name filter instance
    var nameFilterInstance = api.getFilterInstance('name');

    All of the methods in the IFilter interface (described above) are present, assuming the underlying filter implements the method. Your custom filters can add their own methods here that ag-Grid will not use but your application can use. What these extra methods do is up to you and between your customer filter and your application.

    Text Filter Component Methods

    In addition to implementing the IFilter interface, the text filter also provides the following API methods:

    • getType(): Gets the type.
    • setType(string): Sets the type.
    • getFilter(): Gets the filter text.
    • setFilter(string): Sets the filter text.

    The available types for the text filter are the strings: 'contains', 'equals', 'notEquals', 'startsWith' and 'endsWith'.

    So for example, you can set the text of the 'name' filter to start with 'bob' as follows:

    var nameFilter = api.getFilterInstance('name');
    nameFilter.setType('startsWith');
    nameFilter.setFilter('bob');

    Or alternatively, you could just use the setModel() method as part of the main IFilter interface as follows:

    var nameFilter = api.getFilterInstance('name');
    var model = {type: 'startsWith', filter: 'bob'};
    nameFilter.setModel(model);

    Number Filter Component Methods

    Similar to the text filter, the number filter also provides the following API methods:

    • getType(): Gets the type.
    • setType(string): Sets the type.
    • getFilter(): Gets the filter text.
    • setFilter(number): Sets the filter text.

    Date Filter Component Methods

    Similar to the text and number filter, the number filter also provides the following API methods:

    • getDateFrom(): Gets the filter date as string with the format yyyy-mm-dd. If the filter type is "in range", it returns the first date from the range.
    • setDateFrom(dateAsString): Sets the date from. The format of the string must be yyyy-mm-dd.
    • getDateTo(): Gets the second filter date of an "in range" filter as string with the format yyyy-mm-dd, if the filter type is not "in range", then this returns null
    • setDateTo(dateAsString): Sets the date to of an "in range" filter. The format of the string must be yyyy-mm-dd.
    • getFilterType(): Gets the current type of the filter, the possible values are: equals, notEquals, lessThan, greaterThan, inRange.
    • setFilterType(filterName): Sets the current type of the filter, it can only be one of the acceptable types of date filter.

    The available types for the text filter are the strings: 'equals', 'notEqual', 'lessThan', 'lessThanOrEqual', 'greaterThan' and 'greaterThanOrEqual'.

    Example Filter API

    The example below shows controlling the country and age filters via the API.

    The example also shows 'gridApi.destroyFilter(col)' which completely destroys a filter. Use this is if you want a filter to be created again with new initialisation values.

    (Note: the example uses the enterprise set filter).

    Reset Individual Filters

    You can reset a filter to it's original state by getting the filter instance and then performing the action that makes sense for the filter type.

    For all the filter types the sequence would be:

    • var filterComponent = gridOptions.api.getFilterInstance('filter_name');
    • perform reset action for filter type
    • gridOptions.api.onFilterChanged();

    The following are the appropriate methods for the corresponding filter types:

    Filter Type Action
    number filterComponent.setFilter(null);
    text filterComponent.setFilter(null);
    set filterComponent.selectEverything();

    Reset All Filters

    You can reset all filters by doing the following:

    gridOptions.api.setFilterModel(null);
    

    Get / Set All Filter Models

    It is possible to get and set the state of all the filters via the api methods gridOptions.api.getFilterModel and gridOptions.api.setFilterModel. These methods manage the filters states via the getModel and setModel methods of the individual filters.

    This is useful if you want to save the filter state and apply it at a later state. It is also useful for server side filtering, where you want to pass the filter state to the server.

    Example Get / Set All Filter Models

    The example below shows getting and setting all the filter models in action. The 'save' and 'restore' buttons mimic what you would do to save and restore the state of the filters. The big button (Name = 'Mich%'... etc) shows how you can hand craft a model and then set that into the filters.

    (Note: the example uses the enterprise set filter).