简体   繁体   English

如何在AG-Grid中设置列的动态字段?

[英]How to set a dynamic field of a column in AG-Grid?

Let's say in the example below, instead of having 3 distinct columns for medals (gold, silver, and bronze), I'd like to only have one column for all the different medals. 让我们在下面的示例中说,我不想为奖牌(金,银和铜牌)设置3个不同的列,而我想对所有不同的奖牌只设置一个列。


(I know this is a completely unrealistic example but for the sake of learning concepts) I'd like to display the: (我知道这是一个完全不现实的示例,但是为了学习概念)我想展示一下:

  • gold medals ONLY when the age of the athlete is less than 20 (19 and younger) 仅当运动员的年龄小于20岁(19岁及以下)时获得金牌

  • silver medals when the athlete's age is between 20 and 30 (including 20 and 30) 运动员年龄在20到30岁(包括20到30岁)之间的银牌

  • bronze medals if the athlete's age is above 30 (31 and above). 如果运动员的年龄在30岁以上(31岁及以上),则可获得铜牌。

And only have one column called 'Medals'. 并且只有一列称为“奖章”。


this.columnDefs = [
  {
    headerName: "Athlete",
    field: "athlete"
  },
  {
    headerName: "Sport",
    field: "sport"
  },
  {
    headerName: "Age",
    field: "age",
    type: "numberColumn"
  },
  {
    headerName: "Year",
    field: "year",
    type: "numberColumn"
  },
  {
    headerName: "Date",
    field: "date",
    type: ["dateColumn", "nonEditableColumn"],
    width: 200
  },

  {
    headerName: "Gold",
    field: "gold",
  },
  {
    headerName: "Silver",
    field: "silver",
  },
  {
    headerName: "Bronze",
    field: "bronze",
  }
];

Full example of plunker is here: https://plnkr.co/edit/R0JFJwXuyiM7320rNTtx?p=preview unk客的完整示例在这里: https ://plnkr.co/edit/R0JFJwXuyiM7320rNTtx?p = preview

You can use valueGetter for this purpose. 您可以将valueGetter用于此目的。 ValueGetter is a function which returns the value for the column and gets an argument of type ValueGetterParams . ValueGetter是一个函数,它返回列的值并获取ValueGetterParams类型的参数。

    {
      headerName: "Medals",
      valueGetter: (params) => {
        if (params.data.age < 20) {
          return params.data.gold;
        } else if (params.data.age >= 20 && params.data.age < 30) {
          return params.data.silver;
        } else if (params.data.age > 30) {
          return params.data.bronze;
        } else {
        return '';
        }
      },
      type: ["nonEditableColumn"],
      width: 200
    }

Here's a plunker of the working demo - https://plnkr.co/edit/okKOsICJ0GHyHnjh8VRY?p=preview 这里的工作演示的plunker - https://plnkr.co/edit/okKOsICJ0GHyHnjh8VRY?p=preview

Read more about valueGetters here - https://www.ag-grid.com/javascript-grid-value-getters/#value-getter 了解更多关于valueGetters这里- https://www.ag-grid.com/javascript-grid-value-getters/#value-getter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM