1

I am using ChartJS to display numerical values and I am looking to modify the Axes labels to display with commas. I want to do so by having the chart config look like:

var xyValues = [ {x:50, y:7}, {x:60, y:8}, {x:70, y:8}, {x:80, y:9}, {x:90, y:9}, {x:100, y:9}, {x:110, y:10}, {x:120, y:11}, {x:130, y:14}, {x:140, y:14}, {x:150, y:15} ]; var chartConfig = { type: "scatter", data: { datasets: [{ pointRadius: 4, pointBackgroundColor: "rgb(0,0,255)", data: xyValues }] }, options: { legend: {display: false}, scales: { xAxes: [{ ticks: { min: 40, max:1000, // What I need to pass to the child callback: function(value) { return value.toLocaleString(); }, } }], yAxes: [{ticks: {min: 6, max:16}}], } } }; new window.Chart(ctx, chartConfig); 

The chart builds correctly with the commas when done in the same component. My issue is that I wish to create the chart config in a parent component, then pass the config to a child component that will build the chart.

See the following psuedo code:

<!-- Inside Parent component --> <c-chart chart-config={chartConfig}></c-chart> 
// Inside Chart Child Component @api chartConfig; chart; ... initChart(){ // Get context etc this.chart = new window.chart(ctx, this.chartConfig); } 

The child component does not run the callback function like the original could. What can I do to allow the child to run chartConfig's callback function?

Thank you in advance.

1
  • try running it as eval( 'yourcallback' ) - I think all data that passes through the boundary from parent to child is stringified or otherwise santizied. Commented Nov 30, 2022 at 20:59

1 Answer 1

0

Not sure if this will work for you, but expanding on my comment, you could pass the function as a string like this:

callback: "function (value) { return value.toLocaleString();}" 

Then "hydrate" it in the child:

function saferEval(obj) { return eval?.(`"use strict";(${obj})`); } let localCallback = this.chartConfig.options.scales.xAxes[0].ticks.callback; localCallback = this.saferEval(localCallback); 

(I'm not totally sure if you can use the localCallback reference or if you need to full object path).

This will mean you can define the callback in the parent, and have it run in the child.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.