2

I am using Chart.js with my Ionic 3 Angular app. All works fine, except I am unable to refresh the data for the bar that actually changed.

Here is the code:

ionViewDidLoad(){
    this.barChart = new Chart(this.barCanvas.nativeElement, 
    {
        type: 'bar',
        data: {
            labels: ["Safeway", "CVS", "Walgreens", "Bon Appetit"],
            datasets: [{
                label: "Pepsi",
                backgroundColor: "#002F6F",
                data: this.pepsiData
            }, {
                label: "Coke",
                backgroundColor: "#F50000",
                data: this.cockData
            }, {
                label: "V8",
                backgroundColor: "orange",
                data: [83,19,32,34]
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Brands'
            }
        }
    });
}

A separate button update the data for pepsiData array as:

this.pepsiData[3] = 80;

But this does not refresh the particular bar. The ugly solution I have now is to redraw the entire chart, which looks like a bad solution.

4
  • This is the init function, right? Where is the refresh logic? Where are you triggering refresh? Commented Jul 19, 2017 at 8:19
  • I'd suspect you'd need to be subscribing to something and use an event handler to listen to and repaint your chart based on changed data. If it's from a form be sure to use ReactiveFormsModule. You can subscribe to change events and use that to repaint. Without seeing whole solution and when data changes it's hard to give a definitive answer. Commented Jul 19, 2017 at 8:27
  • 1
    after change data, you need to call this.barChart.update() Commented Jul 19, 2017 at 8:37
  • 1
    thanks @Duannx that's what i needed! Commented Jul 19, 2017 at 13:58

1 Answer 1

2

As mentioned in the Chart.js documentation, you need to call chart.update() if you wish to update the data in your chart after it was created:

http://www.chartjs.org/docs/latest/developers/updates.html

Example of adding data and then updating the chart:

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

After you finish changing the data in your update function, you just need to add the update line of code like the following:

this.pepsiData[3] = 80;
myChart.update();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.