【问题标题】:Conditional 'field' in ag-gridag-grid 中的条件“字段”
【发布时间】:2022-01-19 17:48:40
【问题描述】:

是否可以在ag-grid的columnDefs中实现条件字段?每当 rowData 中有“anotherValue”时,我希望为 columnDefs 中的字段值呈现“anotherField”。

例如我有数据:

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

及列定义:

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

请参阅 stackblitz 示例。任何建议都非常感谢。

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

【问题讨论】:

    标签: angular ag-grid ag-grid-angular


    【解决方案1】:

    您可以使用valueGetter 而不是field 来自定义值。阅读更多关于valueGetter

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

    anotherValueGetter 将是一个检查验证的方法。

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

    StackBlitz

    【讨论】:

    • 这是更好的答案。
    【解决方案2】:

    我不确定它是否支持。如果可以的话,您可以修改您的数据:

    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
    }));
    

    然后你的网格将永远只是“价值”:

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

    查看更新后的 stackblitz:

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

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2021-04-24
      • 1970-01-01
      • 2021-11-08
      • 2022-08-04
      • 2020-05-15
      • 2017-10-17
      • 2021-12-01
      • 2017-12-12
      相关资源
      最近更新 更多