Tulika
Tulika

Reputation: 35

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.

Upvotes: 2

Views: 12753

Answers (3)

bancomat
bancomat

Reputation: 15

You can try to implement it with a custom cellRenderer https://www.ag-grid.com/angular-data-grid/component-cell-renderer/#reference-ICellRendererParams

Upvotes: 0

Louis DeRossi
Louis DeRossi

Reputation: 91

@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'

Upvotes: 3

Pratik Bhat
Pratik Bhat

Reputation: 7614

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: [column],
                    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
        }

Upvotes: 7

Related Questions