Chartjs-Updating ng-charts barchart datasets in angular 2

2👍

After one day of agony I found a working solution:
first you have to import directive:

import {BaseChartDirective} from 'ng2-charts/ng2-charts'

then reference chart in class:

@ViewChild(BaseChartDirective)
public chart: BaseChartDirective;

Now you can access your chart in template with chart object. Then place this code when you want to refresh your chart:

this.chart.ngOnChanges({} as SimpleChanges);

Make sure that you pass empty object as type SimpleChanges. ngOnChanges will redraw chart again only if argument is empty object.

Please note that you have to clone and change referance to datasets before calling ngOnChanges.
In my case I did this to refresh graph:`

this.barChartData = clone;
this.chart.datasets = this.barChartData;
this.chart.ngOnChanges({} as SimpleChanges);`

Leave a comment