angularionic-frameworkchartschart.js

Chart.js - Click event on the bar chart entire category


So I am using Chart.js in my Ionic Angular project and I am able to attached a click event to tap on a specific bar and get the data. In my case, I am rendering 3 bars in each category. For a better user experience, I want to detect the tap anywhere in the bar and use the x-axis value to manipulate things.

Below is the current code:

this.fireProgressionChart = new Chart(this.fireProgressionCanvas.nativeElement, {
    data: {
      datasets: [
      {
        type: 'bar',
        label: 'Expenses',
        data: [],
        backgroundColor: 'rgb(178, 69, 69)',
      }, 
      {
        type: 'bar',
        label: 'Passive Income',
        backgroundColor: 'rgb(12, 133, 75)',
        data: [],
      },
      {
        type: 'bar',
        label: 'Asset + Passive Income',
        backgroundColor: 'rgb(49, 74, 138)',
        data: [],
      }
    ],
    labels: this.getNwProgressionLabels(),
  },
  options: {
    onClick: (event, elements) => {
      if (elements.length > 0) {
        const age = this.fireProgressionChart.data.labels[elements[0].index]
        this.updateFireGapData(age)
      }
    }
  }
})

The event is raised when tapping the bar, but I need to be able to raise the event even outside the bars within the chart grid to see which x-axis value is there.


Solution

  • Refer to Converting Events to Data Values, you should able to get the index of the x-axis category based on your click.

    Next, by providing the xIndex to chart.data.labels, you will get the category name/value.

    onClick: (event, elements, chart) => {
      const xScale = chart.scales['x'];
      const canvasPosition = Chart.helpers.getRelativePosition(event, chart);
      const xIndex = xScale.getValueForPixel(canvasPosition.x);
    
      if (xIndex >= 0 && xIndex < chart.data.labels.length) {
        const category = chart.data.labels[xIndex];
        console.log('In category:', category);
      }
    }
    

    Demo @ StackBlitz