问题
I'm using ng2-charts in my ionic 2 project to draw a line chart. I need to access the chart datapoint collection in the (chartClick) event. For that I need access to the base chart.js object for the chart. Is there a way I can access the chart object?
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]));
}
回答1:
Managed to solve this eventually. Used the app.getComponent() method to get a reference to the ng2-chart object and then to the internal chart.js chart object.
HTML: (added the element 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]));
}
Update on 14-Feb-2017 with @ViewChild
If the above doesn't work (due to angular updates) try this. I didn't test this exact code as I don't have the exact source code anymore. In my current project I'm using angular 2.4 so I know @ViewChild works.
Change the HTML markup to:
<base-chart #mylinechart class="chart" etc..
(notice #mylinechart)
Type script:
At the top: import { Component, ViewChild } from '@angular/core';
And then inside your component class:
@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]));
}
Basically @ViewChild gets you a reference to the component marked by '#mylinechart' in the template. Decorating the chartComponent
variable with @ViewChild
makes it possible to access the chart component via that variable. Please note that references returned by @ViewChild
are only available after 'ngAfterViewInit' life-cycle event. Since my use case is a chart 'click' event, I can safely assume that the view has been initialized by that time.
Reference: Angular @ViewChild
来源:https://stackoverflow.com/questions/36905395/ng2-charts-access-base-chart-object