ng2-charts 访问 chartjs 对象以应用 chartjs 功能 [英] ng2-charts access chartjs object to apply chartjs functions

查看:18
本文介绍了ng2-charts 访问 chartjs 对象以应用 chartjs 功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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);

我尝试了 this 解决方案,但似乎不推荐使用 getComponent() .为了规避这一点,我尝试使用@ViewChild(带和不带ElementRef),这将导致在接收到的对象上未定义属性chart".

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 并强制对每个新数据进行重绘.数据添加和删除本身是在 html 中定义的 @Input 对象 lineChartData 上完成的:[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆