Search code examples
angularag-gridag-grid-angular

Ag-grid : Color a cell in a row without using the Cell Styles property in column definitions


[{
    "uniqueIdentifier": "12345",
    "identifier": "UJHU",
    "latitude": 33.68131385650486,
    "longitude": -83.36814721580595,
    "cycle": "1"
    "speedLimit": "255"
    "customerCode": "Standard",
    "altitude" : 12345
    "modifiedKeys": [
      "speedLimit",
      "altitude"
    ]
  },
   {
    "uniqueIdentifier": "13434",
    "identifier": "UJHU",
    "latitude": 93.68131385650486,
    "longitude": -33.36814721580595,
    "cycle": "2"
    "speedLimit": "255"
    "customerCode": "Standard",
    "altitude" : 12345
    "modifiedKeys": [
      "cycle",
      "latitude"
    ]
  }]

The above Json is feed to Ag-grid. Requirement is to color the cells if it belongs to the column names present under modifiedKeys in the above Json.

I dont want to define it using the Cell Class Rules as given here because I have hundreds of columns in my grid. I want to use something like rowClassRules which can be passed as an input to the Ag-grid. Is that possible ?


Solution

  • I think the Cell Style rules are the way to go. If you have hundreds of columns, and don't want to repeat the duplicate cellStyle function, add this function as a default to the column definitions.

    Use this default column def:

    defaultColDef = {
        cellStyle: function(params) {
            console.log(params);
            if (params.node.data.modifiedKeys.some(x => x == params.colDef.field)) {
              //mark police cells as red
              return { backgroundColor: "green" };
            } else {
              return null;
            }
          }
      }
    

    And pass it to your grid like so:

    <ag-grid-angular 
        style="width: 500px; height: 200px;" 
        class="ag-theme-alpine"
        [rowData]="rowData" 
        [defaultColDef]="defaultColDef"
        [columnDefs]="columnDefs">
    </ag-grid-angular>
    

    Here is a StackBlitz demonstration.