Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically updated ng2-charts

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

like image 535
ulou Avatar asked Aug 22 '16 11:08

ulou


2 Answers

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({});
  }

}
like image 194
Standaa - Remember Monica Avatar answered Sep 27 '22 18:09

Standaa - Remember Monica


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()
}
like image 39
ulou Avatar answered Sep 27 '22 17:09

ulou