ng2-charts: Labels not updating when dynamically trying to change them

I’m using ng2-charts and I’m trying to build support for drilling down into a chart. It shouldn’t be hard, just a matter of handling the click event, then changing the labels and the data and I should be pretty much done. But for some reason, the labels aren’t updating properly. Check out this plnkr: http://plnkr.co/edit/YPYdegwj3yLnS42Kbisd?p=preview

When you click 2006 and then click January, everything still functions. I’m only changing the labels at this point, not the data. As soon as I do change the data, things get weird. Near the bottom of src/app.ts, there’s this piece of code:

// setTimeout(() => {
// 	this.barChartData = this.currentNode.bars; // uncomment this first
// }, 0)

Uncomment the second line so that the data is changed and try drilling down into 2006/January again. When clicking 2006, the labels don’t get updated. Now uncomment the rest of the setTimeout() and you’ll notice that everything works as it should: labels updating, data updating. Beautiful.

But this setTimeout() really should not be necessary. Since it has to do with databinding, I suspect this is an ng2-charts bug and not a chart.js bug.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (1 by maintainers)

Commits related to this issue

Most upvoted comments

here is another work around that works on my end just add a condition on the canvas wrapper element *ngIf=“lineChartLabels.length > 0” to redraw the chart.

                  <div class="chart" *ngIf="lineChartLabels.length > 0">
                    <canvas baseChart height="114"
                            [datasets]="lineChartData"
                            [labels]="lineChartLabels"
                            [options]="chartOptions"
                            [chartType]="lineChartType"
                            [colors]="lineChartColors">
                    </canvas>
                  </div>

@ChrisWorks Consider trying this :

  setTimeout(function () {
          this.chartConfig.data.datasets = [{ data: values }];
this.chartConfig.labels = labels;
    }, 0);

This should work. And as said by @JPtenBerge @zbagley, this is just a work around.