首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ng2-charts访问chartjs对象以应用chartjs函数

ng2-charts访问chartjs对象以应用chartjs函数
EN

Stack Overflow用户
提问于 2017-02-14 02:45:59
回答 1查看 1.5K关注 0票数 3

我使用的是NG2图表,需要更多的控制。

xAxis值范围应该动态变化。要实现这一点,我需要访问NG2-Chart使用的Chart-Object。然后我就可以做this

这基本上归结为两个步骤:

代码语言:javascript
复制
//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“。

查看ng2-charts中的chartjs实现,我可以看到BaseChartDirective控制图表的生成,并将生成的图表存储为一个类属性(this.chart)。但是,我不确定如何在我的组件中访问此属性。

ng2-charts是一个模块,因此是我的@NgModule导入的一部分。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-14 04:04:44

解决方案是直接在指令上使用@ViewChild,并强制对每个新数据进行重绘。数据的添加和删除是在@Input对象lineChartData上完成的,该对象在html中定义如下:[datasets]="lineChartData"

代码:

代码语言:javascript
复制
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({});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42211288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档