3

我正在使用 ng2-charts 并且需要更多控制。

xAxis 值范围应该动态变化。为此,我需要访问 ng2-charts 使用的 Chart-Object。然后我可以这样

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

//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),这将导致在接收到的对象上未定义属性“图表”。

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

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

4

1 回答 1

3

解决方案是直接在指令上使用 @ViewChild 并强制对每个新数据进行重绘。lineChartData数据添加和删除本身是在 html 中定义的 @Input 对象上完成的,如下所示:[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({});
于 2017-02-13T20:04:43.653 回答