Is it possible to update any chart from ng2-charts dynamically? I know there are other libraries like angular2-highcharts, but I would like to handle it using ng2-charts. Main question is how can I redraw chart, after button click? I can resize window and data will be updated, so it have to be any option to do it manually.
https://plnkr.co/edit/fXQTIjONhzeMDYmAWTe1?p=preview
A good way is to get a grip on the chart itself in order to redraw it using the API :
export class MyClass {
@ViewChild( BaseChartDirective ) chart: BaseChartDirective;
private updateChart(){
this.chart.ngOnChanges({});
}
}
I figure it out, maybe its not the best existing option, but it works. We can't update existing chart, but we can create new one, using our existing chart and add new points. We can even get better effect, turning animation of chart off.
Function that solved problem:
updateChart(){
let _dataSets:Array<any> = new Array(this.datasets.length);
for (let i = 0; i < this.datasets.length; i++) {
_dataSets[i] = {data: new Array(this.datasets[i].data.length), label: this.datasets[i].label};
for (let j = 0; j < this.datasets[i].data.length; j++) {
_dataSets[i].data[j] = this.datasets[i].data[j];
}
}
this.datasets = _dataSets;
}
Live demo: https://plnkr.co/edit/fXQTIjONhzeMDYmAWTe1?p=preview
@UPDATE: as @Raydelto Hernandez mentioned in comment below, better solution is:
updateChart(){
this.datasets = this.dataset.slice()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With