How to access class variables inside QuickChart configuration?

115 Views Asked by At

I have the following callback function inside my QuickChart instance configuration. I just want to format the value using toLocaleString() method to format a number (3400) to currency (3,400).

The problem is that I can't pass a variable to inside the callback function:

export class MoneyComponent implements OnInit {
    language: string = localStorage.getItem('language'); // de-DE

    ngOnInit(): void { 
        const myChart = new QuickChart();
        myChart.setConfig({
            type: 'bar',
            data: { // etc... },
            options: {
                scales: {
                    yAxes: [{
                        id: 'Left',
                        ticks: {
                            fontSize: 10,
                            callback: (value) => value.toLocaleString(this.language)
                        },
                    }]
                }
            }
        })
    }
}

value.toLocaleString(this.language) it doesn't format the currency because this.language variable doesn't exist for the callback function. If I add the string instead of variabile like this, it works:

callback: (value) => value.toLocaleString('de-DE')

I'm using the arrow function so it should read the variable but it doesn't. Why?

I also tried to use a variable without this keyword but I get this error:

Chart error ReferenceError: a is not defined

const language = localStorage.getItem('language');
ngOnInit(): void { 
        const myChart = new QuickChart();
        myChart.setConfig({
                //....
                callback: (value) => value.toLocaleString(language)
1

There are 1 best solutions below

0
On

Because QuickChart renders the chart on the server side, it doesn't have access to your local variable. You can think of everything in setConfig as though it's passed as a string rather than a function.

The most straightforward thing to do here is just pass the config as a string, and interpolate the language value:

        myChart.setConfig(`{
            type: 'bar',
            data: { // etc... },
            options: {
                scales: {
                    yAxes: [{
                        id: 'Left',
                        ticks: {
                            fontSize: 10,
                            callback: (value) => value.toLocaleString('${language}')
                        },
                    }]
                }
            }
        }`)

There are some alternative approaches in the QuickChart docs.