[Chartjs]-Ng2-charts access base chart object

2👍

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

Leave a comment