Ag-grid highlight cell logic not working properly
Asked Answered
E

1

6

I created an editable grid using ag-grid and I need to highlight the cells that were changed. I added the following code:

    (cellValueChanged)="onDemandsCellValueChanged($event)"

And the method:

    onDemandsCellValueChanged(params): void {
    if (params.oldValue === params.newValue) {
      return;
    }

    params.data.modified = true; // add modified property so it can be filtered on save

    const column = params.column.colDef.field;
    params.column.colDef.cellStyle = { 'background-color': '#e1f9e8' }; // highlight modified cells
    params.api.refreshCells({
      force: true,
      columns: [column],
      rowNodes: [params.node],
    });
  }

The cell is highlighted but when I scroll up and down all the cell from that column are highlighted.

You can check the behavior on stackblitz.

Also if you have a better way of doing this I'm open to new solutions.

Expectant answered 13/12, 2020 at 9:5 Comment(0)
M
4

I understand your problem You can achieve what you want like this - you should use cellStyle in your column definition as showing in docs and for this code is below

cellStyle: params => {
      if (
        params.data["modifiedRow" +
                     params.node.rowIndex +"andCellKey"+ 
                     params.column.colDef.field]
      ) {
        return { backgroundColor: "#e1f9e8" };
      } else {
        return null;
      }
    },

and after that in this function onDemandsCellValueChanged please add and modify this property modified as true and change your function like this as shown below

onDemandsCellValueChanged(params): void {
    if (params.oldValue === params.newValue) {
      return;
    }
    const column = params.column.colDef.field;
    params.data["modifiedRow" + params.rowIndex + "andCellKey" + column] = true;
    params.api.refreshCells({
      force: true,
      columns: [column],
      rowNodes: [params.node]
    });
  }

Now it should work even when you scroll. Here is complete working Example on stackblitz

Macaco answered 21/12, 2020 at 12:55 Comment(4)
Thanks for your answer! This fixed the up and down scrolling problem. But now it happens when I scroll to the right or left. You can check this behavior on your stackblitz example. Do you have a solution for this?Expectant
Hi @NicuVlad, I have updated the example now you can try upper working Example on stackblitz and if you find this answer helpful please accept this answer.Macaco
Thanks! This was the best solution I could find for highlighting modified cells. However, it breaks down when deleting rows. Any idea how to fix this?Schreck
There is no need to add the row number to the modified key because params.data contains only data of the modified row. Omitting the row number makes this also work when rows are deleted (otherwise, highlighting breaks due to changing row numbers).Schreck

© 2022 - 2024 — McMap. All rights reserved.