[Chartjs]-Chart Click Event – Clicking label of doughnut chart, doesn't return label ng2-charts

3πŸ‘

βœ…

you can access your chart via @ViewChild. You set already a local reference in your HTML.

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

This one is containing the labels in the legend.

If you pass some options in your canvas element, then you can manipulate the onClick behavior, too.

<canvas #chart baseChart
    ...
    [options]="chartOptions">
</canvas>

In your .ts-file you create the chartOptions containing a onClick behavior. This will overwrite the default behavior.
For example you could sum up the values for a specific label, using its index.

public chartOptions: ChartOptions = {
  legend: { 
    onClick: (e, i) => {
      console.log(this.chart.data[i.index].reduce((total, next) => total+next));
    }
  }
}

Don’t forget to import

import { ..., ChartOptions } from 'chart.js';
import { ..., BaseChartDirective } from 'ng2-charts';

Here is the modified code.
Hope that helps you.

Leave a comment