在angular 2中更新ng-charts条形图数据集 [英] Updating ng-charts barchart datasets in angular 2
问题描述
如何从angular2更新条形图?我试图将新条目添加到 [datasets] = barChartData
模板中,图形如下所示:
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>
我尝试了以下推荐方法:
1)直接更改数据集变量-克隆了数据,更改它,然后分配它。这样,我可以更改/更新现有数据,但不能将新条目添加到数据集。
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,我向构造函数添加了私有引用:ChangeDetectorRef,并称为 ref.detectChanges()
进行更新。但没有运气。我也尝试过使用ApplicationRef。
2) ChangeDetectorRef, I added private ref: ChangeDetectorRef to constructor and called ref.detectChanges()
on updates. but no luck. I also tried using ApplicationRef.
在两种情况下,在调试窗口中,我都可以看到ts文件中的barChartData已更新为新值,而template(html)却没有
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.
推荐答案
经过一天的痛苦,我找到了一个可行的解决方案:
首先您必须导入指令:
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);
请确保您将空对象作为SimpleChanges类型传递。仅当参数为空对象时,ngOnChanges才会再次重绘图表。
Make sure that you pass empty object as type SimpleChanges. ngOnChanges will redraw chart again only if argument is empty object.
请注意,您必须在调用ngOnChanges之前克隆并更改对数据集的引用。
在我的情况下,我这样做是为了刷新图形:`
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);`
这篇关于在angular 2中更新ng-charts条形图数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!