Search code examples
angularag-gridag-grid-angular

Conditional 'field' in ag-grid


Is it possible to achieve conditional field in columnDefs in ag-grid? I want whenever there is 'anotherValue' in rowData to render 'anotherField' for the field value in columnDefs.

Example I have data:

this.gridOptions.rowData = [
  { id: 5, value: 10 },
  { id: 10, value: 15 },
  { id: 15, value: 20, anotherValue: 500 },
];

And column definition:

this.gridOptions.columnDefs = [
  {
    headerName: 'ID',
    field: 'id',
    width: 100,
  },
  {
    headerName: 'Value',
    field: 'anotherValue' ? 'anotherValue' : 'value', //this part doesn't work
    cellRendererFramework: RedComponentComponent,
    width: 100,
  },
];

Please see the stackblitz example. Any suggestion is really appreciated.

https://stackblitz.com/edit/angular-ag-grid-angular-hzr31v?file=app/my-grid-application/my-grid-application.component.ts


Solution

  • You can use valueGetter instead of field for custom values. Read more about valueGetter

    this.gridOptions.columnDefs = [
          {
            headerName: 'ID',
            field: 'id',
            width: 100,
          },
          {
            headerName: 'Value',
            valueGetter: this.anotherValueGetter, // THIS PART 
            cellRendererFramework: RedComponentComponent,
            width: 100,
          },
        ];
    

    anotherValueGetter will be a method that checks the validation.

      anotherValueGetter(params) {
        return params.data.anotherValue? params.data.anotherValue : params.data.value;
      }
    

    See the StackBlitz