Updating ng-charts barchart datasets in angular 2

别说谁变了你拦得住时间么 提交于 2020-01-17 06:45:46

问题


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


来源:https://stackoverflow.com/questions/44798189/updating-ng-charts-barchart-datasets-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!