ng2-charts 访问 chartjs 对象以应用 chartjs 函数
ng2-charts access chartjs object to apply chartjs functions
我正在使用 ng2-charts 并且需要更多控制。
xAxis 值范围应动态变化。为此,我需要访问 ng2-charts 使用的 Chart-Object。然后我可以做 this
基本上可以归结为两个步骤:
//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),这会导致 属性 "chart" 在接收到的对象上未定义。
查看 ng2-charts 中的 chartjs 实现,我可以看到 BaseChartDirective 控制图表的生成并将生成的图表存储为 class 属性 (this.chart)。但是我不确定如何在我的组件中访问这个 属性。
ng2-charts 是一个模块,因此是我的@NgModule 导入的一部分。
解决方案是直接在指令上使用@ViewChild,并强制使用每个新数据重绘。数据添加和删除本身是在 html 中定义的 @Input 对象 lineChartData
上完成的,如下所示:[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 并且需要更多控制。
xAxis 值范围应动态变化。为此,我需要访问 ng2-charts 使用的 Chart-Object。然后我可以做 this
基本上可以归结为两个步骤:
//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);
我尝试了
查看 ng2-charts 中的 chartjs 实现,我可以看到 BaseChartDirective 控制图表的生成并将生成的图表存储为 class 属性 (this.chart)。但是我不确定如何在我的组件中访问这个 属性。
ng2-charts 是一个模块,因此是我的@NgModule 导入的一部分。
解决方案是直接在指令上使用@ViewChild,并强制使用每个新数据重绘。数据添加和删除本身是在 html 中定义的 @Input 对象 lineChartData
上完成的,如下所示:[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({});