ng2-charts icon indicating copy to clipboard operation
ng2-charts copied to clipboard

Dynamic values getting updated in dataset but not redrawing chart

Open rohanc202 opened this issue 5 years ago • 2 comments

I am using chart.js with ng2-chart where i have to update dataset on button click.

This is how i am reassigning the dataset and labels ;


this.mfData.getMFData('http://www.mocky.io/v2/5ddcf6143400000f55eae607').subscribe(res => {
  res.data.Prices.forEach(element => {
    this.fundData.push(parseInt(element.v));
    this.fundLabel.push(element.d);
  });
  this.lineChartData = [{
      data: this.fundData,
      label: 'Series A',
      lineTension: 0,
      pointRadius: [4, 4, 4, 4],
      borderWidth: 6,
      pointHoverBorderWidth: 8
    }];
  this.lineChartLabels = this.fundLabel;
  this.testChart.chart.update();
});

HTML Code :

    <canvas #testChart='base-chart' baseChart *ngIf="showChart"
      [datasets]="lineChartData"
      [labels]="lineChartLabels"
      [options]="lineChartOptions"
      [colors]="lineChartColors"
      [legend]="lineChartLegend"
      [chartType]="lineChartType">
    </canvas>

Value is being assigned to the 'lineChartData' but the graph is not updated, it vanishes after this method call.

rohanc202 avatar Dec 05 '19 13:12 rohanc202

Has anyone found a solution, yet?

abauske avatar Dec 12 '19 15:12 abauske

Without seeing more code this appears to me to actually be an Angular change detection issue. You're subscribed to an observable, but you're also calling update on the chart manually - which is outside of the relevant Angular change detection mechanisms.

I would bet that if you updated this to use the change detector ref to detect changes, your input binding would trigger a change detection cycle in the actual chart component - calling update without change detection means that it's updating against the old value since angular hasn't updated the component with the new data yet.

Basically, try replacing

  this.testChart.chart.update();

with

  this.changeDetectorRef.markForCheck();
  // or....
  this.changeDetectorRef.detectChanges();

and I would imagine this would start working. Note, you'll need to inject the change detector reference into your component fo this to work, obviously.

dudewad avatar Aug 04 '22 15:08 dudewad

Change detection will not detect deeply nested property changes, call the directive instance update method to force a refresh like @dudewad suggested.

santam85 avatar Mar 01 '24 16:03 santam85