Search code examples
ag-gridag-grid-angular

AG-GRID value formatter not working for dynamically generated currency


I am trying to use a value-formatter in my AG-GRID table for displaying currency information.

This works perfectly when I have a hardcoded value in the formatter, in this case the unicode for 'Euros'

currencyFormatter(params) {
  return '\u20ac' + params.value;
}

However, I dont know in advance what currency I will need to format the data in, as it is dynamically generated. If I try an use a value that is available in my component (like below) it doesn't like it!

currencyFormatter(params) {
  return this.currencyUnicode + params.value;
}

There it throws in the console is:

TypeError: Cannot read property 'defaultCurrency' of undefined

It seems like all 'this' component variables are not available inside the currencyFormatter. Is there a way to make this work?


Solution

  • In order to access your component variables, you will have to bind your component context - this to the valueFormatter

    ...
    name : 'Currency',
    field : 'currency',
    valueFormatter: this.currencyFormatter.bind(this) //bind your component's context here
    ...
    
    currencyFormatter(params) {
      return this.currencyUnicode + params.value;
    }
    

    This is a common javascript problem. Here is a good read

    Also, this answer describes the 2 ways you can reference this.