Chart.js & Angular 2 - ng2-charts Custom on Click Event

blubberbo picture blubberbo · Jul 14, 2016 · Viewed 14.6k times · Source

I am trying to implement ng2-charts in my Angular 2 project and I was wondering about creating custom onclick events. Meaning, I want to override the current onclick events on the carts to do some custom functions (redirect to a page, have a modal show up, etc).

Is there a simple way to do this? Is it built in at all?

Any insight would be appreciated it

Answer

Asif Karim Bherani picture Asif Karim Bherani · Mar 5, 2018

I found this solution at https://github.com/valor-software/ng2-charts/issues/489

public chartClicked(e: any): void {
if (e.active.length > 0) {
const chart = e.active[0]._chart;
const activePoints = chart.getElementAtEvent(e.event);
  if ( activePoints.length > 0) {
    // get the internal index of slice in pie chart
    const clickedElementIndex = activePoints[0]._index;
    const label = chart.data.labels[clickedElementIndex];
    // get value by index
    const value = chart.data.datasets[0].data[clickedElementIndex];
    console.log(clickedElementIndex, label, value)
  }
 }
}