javascriptag-gridag-grid-angular

Differences between valuegetter, valueparser and valueformatter - Ag-grid


I am trying to understand what is the correct usecase for ag-grid's valuegetter vs valueformatter vs valueparser ?

https://www.ag-grid.com/javascript-grid-value-getters/

https://www.ag-grid.com/javascript-grid-value-formatters/

https://www.ag-grid.com/javascript-grid-value-parsers/


Solution

  • Value getter should be used when you want to have custom logic when sourcing data for your ag grid field.
    Let's say you have 2 separate fields displaying First Name and Last Name and you want to have a derived field to show full name, you would use a valueGetter for this new field to concatenate First Name and Last Name
    As per docs -

    A Value Getter is a function that gets called allowing values to be pulled from literally anywhere, including executing any expressions you wish along the way

    Example -

       {
        headerName: 'Name',
        colId: 'name',
        valueGetter: function(params) {
          return params.data.First_Name + " " + params.data.Second_Name;
        },
      },
    

    Note that valueGetter gets called instead of colDef.field if you have a valueGetter defined

    Value formatter should be used when you want to format your data for display. This will not affect the underlying data.
    A classic use case is when you want to round numbers for a numeric field.

    Example :

    {
        headerName: 'Price',
        colId: 'price',
        valueFormatter: function (params) {return params.value.toFixed(2) ;}
     },
    

    Value parser should be used when editing cells. It is the inverse of ValueFormatter, it lets you format your data before you set the value for the cell.

    As per docs -

    After editing cells in the grid you have the opportunity to parse the value before inserting it into your data

    A typical use case would be if your number is displayed with commas, you would want to parse it to remove commas when you edit it and setting data to your row.

    Important things to note
    - As of today, the column filters in ag-grid are driven off colDef.field or valueGetter. So if you define valueFormatter for a column, do not expect formatted values to show up in column filters (for set filter). Using valueGetter would make sure column filters match with the displayed data.