ng2-charts
ng2-charts copied to clipboard
Dynamic values getting updated in dataset but not redrawing chart
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.
Has anyone found a solution, yet?
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.
Change detection will not detect deeply nested property changes, call the directive instance update method to force a refresh like @dudewad suggested.