[Chartjs]-Angular 9 chart.js Bar chart Click event

1👍

Attempted with BaseChartDirective from ng2-charts, but it seems unable to get the chart instance, or even without BaseChartDirective, I am also unable to get the chart instance in the onclick function. Unsure whether it is the version (1.6) issue or else.

Thus, I encourage that to use the chart.js library to generate the chart in order to able to get the chart instance instead of the ng2-charts library.

This requires some changes to migrate from ng2-charts to chart.js.

To generate the chart via chart.js:

public barChartOptions: any = {
    responsive: true,
    scaleShowVerticalLines: false,
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      x: {
        stacked: true,
        ticks: {
          beginAtZero: true,
          maxRotation: 0,
          minRotation: 0,
        },
      },
      y: {
        stacked: true,
      },
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
        font: {
          size: 10,
        },
      },
    },
    onClick: function (evt, elements, chart) {
      const bars = chart.getElementsAtEventForMode(
        evt,
        'nearest',
        { intersect: true },
        true
      );
      if (bars.length === 0) return; // no bars

      const bar = bars[0];

      // Get index and label text
      const index = bar.index;
      const label = chart.data.labels[index];
      let selectedDataset = chart.data.datasets[bar.datasetIndex];

      console.log('Selected label:', label);
      console.log('Selected sub-label:', selectedDataset.label);
      console.log("Selected sub-label's value:", selectedDataset.data[index]);
    },
  };

ngOnInit() {
  new Chart('baseChart', {
      type: <ChartType>this.barChartType,
      options: this.barChartOptions,
      data: {
        datasets: this.barChartData,
        labels: this.barChartLabels,
      },
    });
}
<canvas
  id="baseChart"      
></canvas>

On the above code, you need the onclick function with the getElementsAtEventForMode method in order to get the selected bar, credit to this answer on ChartJs how to get from multiple dataset which dataset bar is clicked.

Demo @ StackBlitz

Leave a comment