Jett
Jett

Reputation: 880

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.


(I know this is a completely unrealistic example but for the sake of learning concepts) I'd like to display the:

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

Upvotes: 1

Views: 1746

Answers (1)

abd995
abd995

Reputation: 1839

You can use valueGetter for this purpose. ValueGetter is a function which returns the value for the column and gets an argument of type 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

Read more about valueGetters here - https://www.ag-grid.com/javascript-grid-value-getters/#value-getter

Upvotes: 2

Related Questions