Using mathjs expressions with ag-grid

123 Views Asked by At

ag-grid allows string expressions in column valueGetters. For example:

{
  field: 'r',
  headerName: 'Radius'
},
{
  field: 'circumference',
  valueGetter: 'Math.PI * data.r ** 2',
}

I am wondering if the expression parser can be switched to mathjs because its syntax is much nicer. For example, the same expression above can be written as pi r ^ 2. How can I do this?

I have a workaround to achieved this by using a ValueGetter function, but that defeats the purpose of defining the expression in the column definition. See below:

import { evaluate } from 'mathjs';


const evaluateExpression = (params: ValueGetterParams) => {
  return evaluate('pi r ^ 2', params.data);
};

// Column definitions
{
  field: 'r',
  headerName: 'Radius'
},
{
  field: 'circumference',
  valueGetter: evaluateExpression,
}

Edit

To clarify, the workaround uses a valueGetter function, which means that the column definitions cannot be stored as a JSON object, which is what I am after. From the AG Grid docs:

The advantage of expressions are that they keep your column definitions as simple JSON objects (just strings, no functions) which makes them candidates for saving in offline storage (eg storing a report definition in a database).

1

There are 1 best solutions below

1
Mara Tata San On

Do you need it as a string expression?

Why don't you just define it like the code below if you want to define the expression in the column definition?

// Column definition

{
  field: 'circumference',
  valueGetter: (p) => evaluate('pi r ^ 2', p.data),
}