我正在使用ng2-charts在我的 ionic 2 项目中绘制折线图。我需要访问 (chartClick) 事件中的图表数据点集合。为此,我需要访问图表的基本 Chart.js 对象。有没有办法访问图表对象?
HTML:
<base-chart class="chart"
[data]="chartData"
[labels]="chartLabels"
[options]="lineChartOptions"
[colours]="lineChartColours"
[legend]="lineChartLegend"
[chartType]="chartType"
(chartClick)="chartClicked($event)"></base-chart>
typescript :
chartClicked(e: any) {
var chart = //reference to base chart object.
var points = chart.getPointsAtEvent(e);
alert(chart.datasets[0].points.indexOf(points[0]));
}
最佳答案
最终成功解决了这个问题。使用app.getComponent()方法获取对ng2-chart对象的引用,然后获取内部chart.js图表对象的引用。
HTML:(添加了元素 id 'mylinechart')
<base-chart id="mylinechart" class="chart"
[data]="chartData"
[labels]="chartLabels"
[options]="lineChartOptions"
[colours]="lineChartColours"
[legend]="lineChartLegend"
[chartType]="chartType"
(chartClick)="chartClicked($event)"></base-chart>
typescript :
constructor(private app: IonicApp) {
}
chartClicked(e: any) {
var chartComponent = this.app.getComponent('mylinechart'); //ng2-chart object
var chart = chartComponent.chart; //Internal chart.js chart object
console.log(chart.datasets[0].points.indexOf(e.activePoints[0]));
}
2017 年 2 月 14 日使用 @ViewChild 更新
如果上述方法不起作用(由于角度更新),请尝试此操作。我没有测试这个确切的代码,因为我不再有确切的源代码。在我当前的项目中,我使用的是 Angular 2.4,所以我知道 @ViewChild 可以工作。
将 HTML 标记更改为:
<base-chart #mylinechart class="chart" etc..
(注意#mylinechart)
输入脚本:
顶部:import { Component, ViewChild } from '@angular/core';
然后在你的组件类中:
@ViewChild('mylinechart')
private chartComponent: any;
constructor(private app: IonicApp) {
}
chartClicked(e: any) {
var chart = this.chartComponent.chart; //Internal chart.js chart object
console.log(chart.datasets[0].points.indexOf(e.activePoints[0]));
}
基本上,@ViewChild 会为您提供对模板中标有“#mylinechart”的组件的引用。装饰chartComponent
变量为 @ViewChild
使得可以通过该变量访问图表组件。请注意 @ViewChild
返回的引用仅在“ngAfterViewInit”生命周期事件之后可用。由于我的用例是图表“单击”事件,因此我可以放心地假设 View 当时已初始化。
关于chart.js - ng2-charts 访问基础图表对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905395/