【问题标题】:How to change styling of cells that has been edited in ag-Grid?如何更改已在 ag-Grid 中编辑的单元格的样式?
【发布时间】:2020-08-13 11:08:21
【问题描述】:

我想标记已编辑的单元格,以便用户可以看到哪些单元格已被触摸和更改。我知道有一个单元格闪光灯选项,但这只是稍微改变了背景颜色。我想要的是在编辑完成后改变背景颜色。

似乎找不到任何有关访问的特定文档,例如 html 元素或受影响单元格的样式。

有人有什么想法吗?

【问题讨论】:

    标签: javascript angular ag-grid


    【解决方案1】:

    您可以使用ColDef.onCellValueChanged 来检测是否有变化并使用GridApi.refreshCells() 相应地更新单元格样式

    const columnDefs = [{
      headerName: "Athlete",
      field: "athlete",
      onCellValueChanged: this.markAsDirty
    },...]
    
    ...
    
    private markAsDirty(params: ICellRendererParams) {
      params.colDef.cellClass = (p) =>
        p.rowIndex.toString() === params.node.id ? "ag-cell-dirty" : "";
    
      params.api.refreshCells({
        columns: [params.column.getId()],
        rowNodes: [params.node],
        force: true // without this line, the cell style is not refreshed at the first time
      });
    }
    

    在您的 css 文件中

    :host ::ng-deep .ag-cell-dirty {
      background-color: rgba(255, 193, 7, 0.5) !important;
    }
    

    如果您希望将此行为应用于所有列,您可能还想使用defaultColDef

    this.gridOptions = {
      defaultColDef: {
        editable: true,
        onCellValueChanged: this.markAsDirty
      },
    };
    

    现场演示

    【讨论】:

      【解决方案2】:

      我在我正在做的一个项目上做了这个。

      您可以在列定义 (https://www.ag-grid.com/javascript-grid-cell-styles/) 中定义一个 cellClass 属性,它可以使用 params: CellClassParams 进行回调函数。

      所以尝试做:

      cellClass: (params: CellClassParams) => {
        // you need to have a handle on the original untouched data
        // See if the original value does not equal the modified value in params
        // For shortness, I will write pseudocode
         if (originalValue !== modifiedValue) {
           return 'ag-cell-was-modified';
         }
      }
      

      如果许多列是可编辑的,您可能希望为每一列使用cellClass 的可重复使用函数。

      无论单元格是否被修改,都应该有条件地应用 ag-cell-was-modified 类,并且在您的 style.scss 或主样式表中,您可以添加:

      .ag-cell-was-modified {
        background: red;
      }
      

      当然,如果你使用的是 SASS,你可以把这个类定义放在更合适的地方。

      【讨论】:

      • 你是怎么做的:“你需要处理原始未触及的数据”??
      • 有一个名为 originalData 的实例变量,并将最初进入网格的数据分配给它。然后当cellClass 被调用时,在参数上你会得到新的值,我假设它上面有一个id。在 originalData 中通过 id 查找此值,并查看该值是否与 params 中的值不同。这可能不是最有效的,如果你想这样做,你应该考虑接受答案的方法。
      猜你喜欢
      • 2019-11-27
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2019-08-24
      • 2020-05-03
      • 2019-12-26
      相关资源
      最近更新 更多