Search code examples
ag-grid-angular

How can I color a cell where I know the row index and field name in ag-grid?


enter image description here
let, row index = 5 & field = 'age' Now, how can color the cell which have row = 5 & field = 'age' in ag-grid? I have tried the last two days but failed to implement this.


Solution

  • I suppose you have an array of objects containing row index and field names:

    rowIndexes = [ 
      { row: 3, field: ['age']}, 
      { row: 5, field: ['name']}, 
      { row: 10, field: ['name', 'salary'] }
    ];
    

    Add cellStyle property to each columnDef:

    {
      headerName: 'Name',
      field: 'name',
      cellStyle: (params) => {
        let rowIndex = params.node.rowIndex;
        if (this.isColoredCell(rowIndex, 'name'))
          return { backgroundColor: 'red' }
        return null;
      }
    }
    ...
    ...
    

    And add your logic to isColoredCell method:

    isColoredCell(rowIndex: number, field: string): boolean {
      let indexes = this.rowIndexes.filter(item => item.row == rowIndex);
      if (indexes.length > 0) {
        let fields = indexes[0].field;
        if (fields.indexOf(field) > -1) {
          return true;
        }
        return false;
      }
      return false;
    }
    

    Hope you can color your cells this way.