Make chartJS labels clickable and get label details

πŸ‘:2

The problem with getElementAtEvent is that it returns a single chart element at the event position (a bar, a point etc.). The tick label is not considered to be a chart element, hence you won’t get any data.

You can define your onClick function as follows instead.

onClick: event => {
  let point = Chart.helpers.getRelativePosition(event, subPerf.chart);
  let xIndex = subPerf.scales['x-axis-0'].getValueForPixel(point.x);
  let label = subPerf.data.labels[xIndex];
  console.log(label + ' at index ' + xIndex);
},

Please have a look at this StackBlitz that uses Angular 6. I hope the same also works for Angular 5.

Leave a comment