Results:
Loading...

React Data Grid: Number Filter

Number Filters allow you to filter number data.

Number Filter

Enabling Number Filters

The Number Filter can be configured as shown below:

const columnDefs = [
    {
        field: 'age',
        // configure column to use the Number Filter
        filter: 'agNumberColumnFilter',
        filterParams: {
            // pass in additional parameters to the Number Filter
        },
    },
];

<AgGridReact columnDefs={columnDefs}></AgGridReact>

Example: Number Filter

The example below shows the Number Filter in action:

  • The first column shows the default Number Filter behaviour.
  • The second column demonstrates Custom Number Support and uses commas for decimals and allows a dollar sign ($) to be included.
  • Floating filters are enabled and also react to the configuration of allowedCharPattern.

Number Filter Parameters

Number Filters are configured though the filterParams attribute of the column definition (INumberFilterParams interface):

allowedCharPattern
string
When specified, the input field will be of type text, and this will be used as a regex of all the characters that are allowed to be typed. This will be compared against any typed character and prevent the character from appearing in the input if it does not match.
buttons
FilterButtonType[]
Specifies the buttons to be shown in the filter, in the order they should be displayed in. The options are:
  • 'apply': If the Apply button is present, the filter is only applied after the user hits the Apply button.
  • 'clear': The Clear button will clear the (form) details of the filter without removing any active filters on the column.
  • 'reset': The Reset button will clear the details of the filter and any active filters on that column.
  • 'cancel': The Cancel button will discard any changes that have been made to the filter in the UI, restoring the applied model.
  • buttons: FilterButtonType[];
    
    type FilterButtonType = 
          'apply' 
        | 'clear' 
        | 'reset' 
        | 'cancel'
    
    closeOnApply
    boolean
    If the Apply button is present, the filter popup will be closed immediately when the Apply or Reset button is clicked if this is set to true.
    Default: false
    debounceMs
    number
    Overrides the default debounce time in milliseconds for the filter. Defaults are:
  • TextFilter and NumberFilter: 500ms. (These filters have text field inputs, so a short delay before the input is formatted and the filtering applied is usually appropriate).
  • DateFilter and SetFilter: 0ms
  • defaultJoinOperator
    JoinOperator
    By default, the two conditions are combined using AND. You can change this default by setting this property. Options: AND, OR
    defaultJoinOperator: JoinOperator;
    
    type JoinOperator = 'AND' | 'OR'
    defaultOption
    string
    The default filter option to be selected.
    filterOptions
    (IFilterOptionDef | ISimpleFilterModelType)[]
    Array of filter options to present to the user. See Filter Options.
    filterOptions: (IFilterOptionDef | ISimpleFilterModelType)[];
    
    interface IFilterOptionDef {
      // A unique key that does not clash with the built-in filter keys. 
      displayKey: string;
      // Display name for the filter. Can be replaced by a locale-specific value using a `localeTextFunc`. 
      displayName: string;
      // Custom filter logic that returns a boolean based on the `filterValues` and `cellValue`. 
      predicate?: (filterValues: any[], cellValue: any) => boolean;
      // Number of inputs to display for this option. Defaults to `1` if unspecified. 
      numberOfInputs?: 0 | 1 | 2;
    }
    
    type ISimpleFilterModelType = 
          'empty' 
        | 'equals' 
        | 'notEqual' 
        | 'lessThan' 
        | 'lessThanOrEqual' 
        | 'greaterThan' 
        | 'greaterThanOrEqual' 
        | 'inRange' 
        | 'contains' 
        | 'notContains' 
        | 'startsWith' 
        | 'endsWith' 
        | 'blank' 
        | 'notBlank'
    
    filterPlaceholder
    FilterPlaceholderFunction | string
    Placeholder text for the filter textbox
    filterPlaceholder: FilterPlaceholderFunction | string;
    
    type FilterPlaceholderFunction = 
          (params: IFilterPlaceholderFunctionParams) => string
    
    
    interface IFilterPlaceholderFunctionParams {
      // The filter option key
      filterOptionKey: ISimpleFilterModelType;
      // The filter option name as localised text
      filterOption: string;
      // The default placeholder text
      placeholder: string;
    }
    
    type ISimpleFilterModelType = 
          'empty' 
        | 'equals' 
        | 'notEqual' 
        | 'lessThan' 
        | 'lessThanOrEqual' 
        | 'greaterThan' 
        | 'greaterThanOrEqual' 
        | 'inRange' 
        | 'contains' 
        | 'notContains' 
        | 'startsWith' 
        | 'endsWith' 
        | 'blank' 
        | 'notBlank'
    
    inRangeInclusive
    boolean
    If true, the 'inRange' filter option will include values equal to the start and end of the range.
    includeBlanksInEquals
    boolean
    If true, blank (null or undefined) values will pass the 'equals' filter option.
    includeBlanksInGreaterThan
    boolean
    If true, blank (null or undefined) values will pass the 'greaterThan' and 'greaterThanOrEqual' filter options.
    includeBlanksInLessThan
    boolean
    If true, blank (null or undefined) values will pass the 'lessThan' and 'lessThanOrEqual' filter options.
    includeBlanksInRange
    boolean
    If true, blank (null or undefined) values will pass the 'inRange' filter option.
    maxNumConditions
    number
    Maximum number of conditions allowed in the filter.
    Default: 2
    numAlwaysVisibleConditions
    number
    By default only one condition is shown, and additional conditions are made visible when the previous conditions are entered (up to maxNumConditions). To have more conditions shown by default, set this to the number required. Conditions will be disabled until the previous conditions have been entered. Note that this cannot be greater than maxNumConditions - anything larger will be ignored.
    Default: 1
    numberParser
    Function
    Typically used alongside allowedCharPattern, this provides a custom parser to convert the value entered in the filter inputs into a number that can be used for comparisons.
    numberParser = (text: string | null) => number | null;
    readOnly
    boolean
    If set to true, disables controls in the filter to mutate its state. Normally this would be used in conjunction with the Filter API. See Read-only Filter UI.
    Default: false

    Custom Number Support

    HTML5 number inputs have mixed browser support and behaviour, particularly around locale-specific nuances, e.g. using commas rather than periods for decimal values. Due to this, the default behaviour of the Number Filter is to use a number input in Chrome and Microsoft Edge, and to use a text input in all other browsers whilst preventing non-numeric characters.

    If you want to override the default behaviour, or allow users to type other characters (e.g. currency symbols, commas for thousands, etc.), the Number Filter allows you to control what characters the user is allowed to type. In this case, a text input is used with JavaScript controlling what characters the user is allowed (rather than the browser). You can also provide custom logic to parse the provided value into a number to be used in the filtering.

    Custom number support is enabled by specifying configuration similar to the following:

    const columnDefs = [
        {
            field: 'age',
            filter: 'agNumberColumnFilter',
            filterParams: {
                allowedCharPattern: '\\d\\-\\,', // note: ensure you escape as if you were creating a RegExp from a string
                numberParser: text => {
                    return text == null ? null : parseFloat(text.replace(',', '.'));
                }
            }
        }
    ];
    
    <AgGridReact columnDefs={columnDefs}></AgGridReact>

    The allowedCharPattern is a regex of all the characters that are allowed to be typed. This is surrounded by square brackets [] and used as a character class to be compared against each typed character individually and prevent the character from appearing in the input if it does not match (in supported browsers).

    The numberParser should take the user-entered text and return either a number if one can be interpreted, or null if not.

    Custom number support can be seen in the Number Filter Example above.

    Number Filter Model

    The Filter Model describes the current state of the applied Number Filter. If only one Filter Condition is set, this will be a NumberFilterModel:

    filterType
    'number'
    Filter type is always 'number'
    filter
    number | null
    The number value(s) associated with the filter. Custom filters can have no values (hence both are optional). Range filter has two values (from and to).
    filterTo
    number | null
    Range filter to value.
    type
    ISimpleFilterModelType | null
    One of the filter options, e.g. 'equals'
    type: ISimpleFilterModelType | null;
    
    type ISimpleFilterModelType = 
          'empty' 
        | 'equals' 
        | 'notEqual' 
        | 'lessThan' 
        | 'lessThanOrEqual' 
        | 'greaterThan' 
        | 'greaterThanOrEqual' 
        | 'inRange' 
        | 'contains' 
        | 'notContains' 
        | 'startsWith' 
        | 'endsWith' 
        | 'blank' 
        | 'notBlank'
    

    If more than one Filter Condition is set, then multiple instances of the model are created and wrapped inside a Combined Model (ICombinedSimpleModel<NumberFilterModel>). A Combined Model looks as follows:

    // A filter combining multiple conditions
    interface ICombinedSimpleModel<NumberFilterModel> {
        filterType: string;
    
        operator: JoinOperator;
    
        // multiple instances of the Filter Model
        conditions: NumberFilterModel[];
    }
    
    type JoinOperator = 'AND' | 'OR';

    Note that in AG Grid versions prior to 29.2, only two Filter Conditions were supported. These appeared in the Combined Model as properties condition1 and condition2. The grid will still accept and supply models using these properties, but this behaviour is deprecated. The conditions property should be used instead.

    An example of a Filter Model with two conditions is as follows:

    // Number Filter with two conditions, both are equals type
    const numberEquals18OrEquals20 = {
        filterType: 'number',
        operator: 'OR',
        conditions: [
            {
                filterType: 'number',
                type: 'equals',
                filter: 18
            },
            {
                filterType: 'number',
                type: 'equals',
                filter: 20
            }
        ]
    };

    Number Filter Options

    The Number Filter presents a list of Filter Options to the user.

    The list of options are as follows:

    Option NameOption KeyIncluded by Default
    EqualsequalsYes
    Not equalnotEqualYes
    Less thanlessThanYes
    Less than or equalslessThanOrEqualYes
    Greater thangreaterThanYes
    Greater than or equalsgreaterThanOrEqualYes
    In rangeinRangeYes
    BlankblankYes
    Not blanknotBlankYes
    Choose OneemptyNo

    Note that the empty filter option is primarily used when creating Custom Filter Options. When 'Choose One' is displayed, the filter is not active.

    The default option for the Number Filter is equals.

    Number Filter Values

    By default, the values supplied to the Number Filter are retrieved from the data based on the field attribute. This can be overridden by providing a filterValueGetter in the Column Definition. This is similar to using a Value Getter, but is specific to the filter.

    filterValueGetter
    string | ValueGetterFunc
    Function or expression. Gets the value for filtering purposes.
    filterValueGetter: string | ValueGetterFunc<TData>;
    
    interface ValueGetterFunc<TData = any> {
        (params: ValueGetterParams<TData>) : any
    }
    
    interface ValueGetterParams<TData = any> {
      // A utility method for getting other column values 
      getValue: (field: string) => any;
      // Row node for the given row 
      node: IRowNode<TData> | null;
      // Data associated with the node 
      data: TData | undefined;
      // Column for this callback 
      column: Column;
      // ColDef provided for this column 
      colDef: ColDef<TData>;
      // The grid api. 
      api: GridApi<TData>;
      // The column api. 
      columnApi: ColumnApi;
      // Application context as set on `gridOptions.context`. 
      context: any;
    }

    Applying the Number Filter

    Applying the Number Filter is described in more detail in the following sections:

    Blank Cells

    If the row data contains blanks (i.e. null or undefined), by default the row won't be included in filter results. To change this, use the filter params includeBlanksInEquals, includeBlanksInLessThan, includeBlanksInGreaterThan and includeBlanksInRange. For example, the code snippet below configures a filter to include null for equals, but not for less than, greater than or in range:

    const filterParams = {
        includeBlanksInEquals: true,
        includeBlanksInLessThan: false,
        includeBlanksInGreaterThan: false,
        includeBlanksInRange: false,
    };

    In the following example you can filter by age and see how blank values are included. Note the following:

    • Column Age has both null and undefined values resulting in blank cells.
    • Toggle the controls on the top to see how includeBlanksInEquals, includeBlanksInLessThan, includeBlanksInGreaterThan and includeBlanksInRange impact the search result.

    Data Updates

    The Number Filter is not affected by data changes. When the grid data is updated, the filter value will remain unchanged and the filter will be re-applied based on the updated data (e.g. the displayed rows will update if necessary).

    Next Up

    Continue to the next section to learn about Date Filters.