Home > Software engineering >  Conditional 'field' in ag-grid
Conditional 'field' in ag-grid

Time:12-17

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

CodePudding user response:

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

CodePudding user response:

I'm not sure if it supports that. You could modify your data though if that's an option:

this.gridOptions.rowData = [
  { id: 5, value: 10 },
  { id: 10, value: 15 },
  { id: 15, value: 20, anotherValue: 500 },
].map(entry => ({
    ...entry,
    value: entry.anotherValue ? entry.anotherValue : entry.value
}));

And then your grid would always just be "value":

this.gridOptions.columnDefs = [
  {
    headerName: 'ID',
    field: 'id',
    width: 100,
  },
  {
    headerName: 'Value',
    field: 'value',
    cellRendererFramework: RedComponentComponent,
    width: 100,
  },
];

See your updated stackblitz:

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

  • Related