Results:
Loading...

JavaScript Data GridParsing Values

After editing cells in the grid you have the opportunity to parse the value before inserting it into your data. This is done using Value Parsers.

Value Parser

For example suppose you are editing a number using the default editor. The result will be a String, however you will probably want to store the result as a number. Use a Value Parser to convert the String to a Number.

const gridOptions = {
    columnDefs: [
        {
            // name is a string, so don't need to convert
            field: 'name',
            editable: true,
        },
        {
            // age is a number, so want to convert from string to number
            field: 'age',
            editable: true,
            valueParser: params => Number(params.newValue)
        }
    ],

    // other grid options ...
}
valueParser
string | ValueParserFunc
Function or expression. Parses the value for saving.
valueParser: string | ValueParserFunc<TData>;

interface ValueParserFunc<TData = any, TValue = any> {
    (params: ValueParserParams<TData>) : TValue
}

interface ValueParserParams<TData = any> {
  // The value before the change 
  oldValue: any;
  // The value after the change 
  newValue: any;
  // Row node for the given row 
  node: IRowNode<TData> | null;
  // Data associated with the node 
  data: TData;
  // 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;
}

The return value of a value parser should be the result of the parse, i.e. return the value you want stored in the data.

Below shows an example using value parsers. The following can be noted:

  • All columns are editable. After any edit, the console prints the new data for that row.
  • Column 'Name' is a string column. No parser is needed.
  • Column 'Bad Number' is bad because after an edit, the value is stored as a string in the data, whereas the data value should be number type.
  • Column 'Good Number' is good because after an edit, the value is converted to a number using the value parser.