0
votes

Is it possible using the framework ag-grid in JS to apply a conditional background color formatting of a cell based on its value such as Excel conditional formatting (eg the second table formatting in this link is a great example of what I am trying to achieve).

Basically, cells containing the highest values are green and tend to be red as they lower, being yellow when they reach the median (the inverse is applied in above link)

As you see, it is not a simple CellClassRules as the cell color depends cell values across the table and not only a specific row or column.

I didn’t find such option on ag-grid documentation.

2
write a function which looks at values for the row, works out which colour each cell should be based on value, and apply a background color, example.ViqMontana
Thanks for the answer. On your example, the formatting is per row. If you check this plnkr.co/edit/kFh0Bir6ul8J3yDx , you can see that in the first row 9 is green, and second row 3 is green. What I need is to have the formatting as if all the number where contained in a unique row, so that low number across the table are red and higher numbers green.user12392864
looks correct to me, the highest value PER ROW will be green, but I'm guessing you want the gradient across the table? You'll just need to tweak the logic to take other rows into account, should be fairly easy.ViqMontana
Yes I would like the gradient across the row and don’t quite know how to tweak the function to get it.user12392864
it does work across the row, the highest value per row is green, the lowest being red. what's the problem?ViqMontana

2 Answers

1
votes

Why don't you use the Gradient Column feature and it will do it all for you with a couple of clicks? https://demo.adaptabletools.com/style/aggridgradientcolumndemo

0
votes

Write a function for the cellStyle and have this function look at each and every value in the table, determine it's ranking, then have it return the relevant colour for the cell, i.e. the lower it is, return a more "reddish" colour, the higher it is, return a "greener" colour. Something like this:

function myCellStyleFunction(params) {
  const totalCellCount = params.api.getDisplayedRowCount() * columnsCount;
  let allValuesInTable = [];

  rowData.forEach((x) => {  
    const valuesForRow = Object.keys(x).map(function (k) {
      return x[k];
    });
    allValuesInTable = allValuesInTable.concat(valuesForRow);
  });
  
  const valuesForTableOrdered = allValuesInTable.sort(function (a, b) {
    return a - b;
  });
  
  const valueIndex = valuesForTableOrdered.indexOf(params.value);
  console.log(valueIndex)
  debugger;
  const bgColour = generateColor('#FF0000','#00FF00',totalCellCount,valueIndex)

  return { backgroundColor: '#' + bgColour };
}

And apply this cellStyle in defaultColDef so it is applied to every cell.

Demo.