Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 911
blubberbo Avatar asked Jul 14 '16 16:07

blubberbo


1 Answers

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)
  }
 }
}
like image 169
Asif Karim Bherani Avatar answered Oct 19 '22 23:10

Asif Karim Bherani