ag Grid change cell color on Cell Value Change

I am trying to change cell color when cell old value != cell new value in a grid.

I’ve tried:

if (e.oldValue === e.newValue)    {   
    e.colDef.cellStyle = function(e) {return { backgroundColor: 'green' };
}

But when save is hit or data is reloaded, it changes the column color to green.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Ag-grid does not have a built in feature to highlight edited cells. you can solve this in 2 ways.

  1. Dynamically updating cell Style –

    onCellValueChanged(params) {
      if (params.oldValue !== params.newValue) {
          var column = params.column.colDef.field;
                params.column.colDef.cellStyle = { 'background-color': 'cyan' };
                params.api.refreshCells({
                    force: true,
                    columns: 
    , rowNodes: [params.node] }); }}
  2. Using a combination of cellClassRules, an edit flag and onCellValueChanged -

    • Define a css class for edited cell.
      .green-bg {background-color: olivedrab;}

    • Define cellClassRules for the column which applies style based on flag you update on edit.
      cellClassRules: {
      'green-bg': (params) => { return params.data.isEdited}
      }

    • Then you set the flag in your onCellValueChanged something like this -
onCellValueChanged(params) {
          if (params.oldValue !== params.newValue) {
             params.data.isEdited = true; // set the flag
          }
          params.api.refreshCells(); //causes styles to be reapplied based on cellClassRules
        }

Solution 2

@Coding Professor.
The correct usage for way 1 is as follows:

if (params.oldValue !== params.newValue) {
        params.colDef.cellStyle = (p) =>
            p.rowIndex.toString() === params.node.id ? {'background-color': 'red'} : "";

        params.api.refreshCells({
            force: true,
            columns: [params.column.getId()],
            rowNodes: [params.node]
        });
    }

With way 2, I think this is incorrect way. Especially when you use columnGroupShow: 'open'

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply