emn178 / angular2-chartjs

Chart.js component for Angular2
MIT License
95 stars 21 forks source link

Click on datapoint #29

Closed gentle9 closed 6 years ago

gentle9 commented 6 years ago

Hi,

it is possible to add a click listener to the datapoints? I want to make the bars in the chart clickable. I know that I can add (click) to the chart element but I need it only on a datapoint.

emn178 commented 6 years ago

please see Chart.js document http://www.chartjs.org/docs/latest/developers/api.html .getElementsAtEvent(e) section

gentle9 commented 6 years ago

I am trying to get the datapoints with .getElementsAtEvent(e) but it doesn´t work. I only get an empty array.

This is my html <chart [type]="type" [data]="data" [options]="options" (click)="clickChart($event)"></chart>

And this is my ts

 @ViewChild(ChartComponent) myChart: ChartComponent;
  type = 'line';
data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "My First dataset",
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};
options = {
  responsive: true,
  maintainAspectRatio: false
};
clickChart(event) {
  console.log(this.myChart.chart.getElementAtEvent(event));
}
YaroshIS commented 6 years ago

Any solutions? I have the same problem

emn178 commented 6 years ago

After test, Chart.js can't get correct result if binding event on parent element. I added custom events to support this feature at v0.5.0.

tdn commented 5 years ago

Don't use the angular (click) listener, but rather the one defined in the options, as such:

options = {
 responsive: true,
 maintainAspectRatio: false,
 onClick: () => {
      console.log(this.myChart.chart.getElementAtEvent(event));
 }
}

That worked for me