ag 网格在单元格值更改时更改单元格颜色

IT技术 reactjs ag-grid
2021-04-30 04:49:08

当网格中的单元格旧值 != 单元格新值时,我试图更改单元格颜色。

我试过了:

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

但是当点击保存或重新加载数据时,它会将列颜色更改为绿色。

2个回答

Ag-grid 没有内置功能来突出显示已编辑的单元格。你可以通过两种方式解决这个问题。

  1. 动态更新单元格样式 -

    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. 使用cellClassRules, 编辑标志和onCellValueChanged- 的组合

    • 为编辑的单元格定义一个 css 类。
      .green-bg {background-color: olivedrab;}

    • 为根据您在编辑时更新的标志应用样式的列定义 cellClassRules。 cellClassRules: { 'green-bg': (params) => { return params.data.isEdited} }

    • 然后你在你的onCellValueChanged东西中设置标志-
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
        }

@编码教授。方式一的正确用法如下:

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]
        });
    }

对于方式2,我认为这是不正确的方式。特别是当你使用 columnGroupShow: 'open'