ng2-charts访问chartjs对象以应用chartjs函数 [英] ng2-charts access chartjs object to apply chartjs functions
问题描述
我正在使用ng2-charts,需要更多控制.
I am using ng2-charts and require more control.
xAxis值范围应动态更改.为此,我需要访问ng2-charts使用的Chart-Object.然后,我可以此
The xAxis value range should change dynamically. To achieve this I need to get access to the Chart-Object used by ng2-charts. Then I can do this
基本上可以归结为两个步骤:
Which basically boils down to two steps:
//Chart-Object
var barChartDemo = new Chart(ctx).Bar(barChartData, {
responsive: true,
barValueSpacing: 2
});
setInterval(function() {
//removing the first dataentry
barChartDemo.removeData();
//adding new data
barChartDemo.addData([dData()], "dD " + index);
index++;
}, 3000);
我尝试了此解决方案,但似乎不赞成使用getComponent().为了避免这种情况,我尝试使用@ViewChild(带有和不带有ElementRef),这将导致在接收到的对象上未定义属性图表".
I tried this solution but it seems that getComponent() is deprecated. To circumvent this I tried to use @ViewChild (with and without ElementRef) which would result in property "chart" being undefined on the received object.
查看ng2-charts中的chartjs实现,我可以看到BaseChartDirective控制着图表的生成并将生成的图表存储为类属性(this.chart).但是我不确定如何在组件中访问此属性.
Looking into the chartjs implementation in ng2-charts I can see that the BaseChartDirective controls the generation of charts and stores the generated chart as a class property (this.chart). However I am not certain how to get access to this property in my component.
ng2-charts是一个模块,因此是我的@NgModule导入的一部分.
ng2-charts is a module and therefore part of my @NgModule imports.
推荐答案
解决方案是直接在指令上使用@ViewChild并强制对每个新数据进行重绘.数据添加和删除本身是在@Input对象lineChartData
上完成的,该对象在html中定义如下:[datasets]="lineChartData"
The solution was using @ViewChild on the directive directly and forcing a redraw with each new data. Dataadding and removing itself was done on the @Input object lineChartData
which is defined in the html like this: [datasets]="lineChartData"
代码:
import { BaseChartDirective } from 'ng2-charts/charts/charts';
export class Example{
@ViewChild(BaseChartDirective) baseChartDir: BaseChartDirective;
public lineChartData: Array<any>;
//call this function whenever you want an updated version of your chart
this.baseChartDir.ngOnChanges({});
这篇关于ng2-charts访问chartjs对象以应用chartjs函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!