Updating ng-charts barchart datasets in angular 2

2019-08-18 07:18发布

问题:

How to update barchart from angular2? I am trying to add new entry on click to [datasets]="barChartData" In template, graph looks like this:

<canvas baseChart #myChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[legend]="barChartLegend"
[chartType]="barChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>

I tried following recommended methods: 1) Changed dataset variable directly - cloned the data , changed it and then assigned it. This way I can change/update exsiting data but I can't add new entry to dataset.

2) ChangeDetectorRef, I added private ref: ChangeDetectorRef to constructor and called ref.detectChanges() on updates. but no luck. I also tried using ApplicationRef.

In both cases, in debug window, I can see that barChartData is updated with new values in ts file, but template(html) is not updated/refreshed.

回答1:

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);`