NiallMitch14
NiallMitch14

Reputation: 1229

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

I have a doughnut chart setup and I would like to use a click event on the label. Using the code from this answer (https://stackoverflow.com/a/49118430/4611941), I am able to trigger a click event when clicking on the chart to return the label and data:

chartClicked (e: any): void {
    debugger;
    if (e.active.length > 0) {
        const chart = e.active[0]._chart;
        const activePoints = chart.getElementAtEvent(e.event);
        if ( activePoints.length > 0) {
            // get the internal index of slice in pie chart
            const clickedElementIndex = activePoints[0]._index;
            const label = chart.data.labels[clickedElementIndex];
            // get value by index
            const value = chart.data.datasets[0].data[clickedElementIndex];
            console.log(clickedElementIndex, label, value)
        }
    }
}

This works perfectly when clicking on the chart data itself as the label is returned and I can then use this value. However when clicking on the label itself above the chart, this code can't get the value of the label clicked (e.active.lenth = 0). However, it still performs it's filtering by removing/adding the data for that label to the doughnut chart.

This is how I currently have my chart setup:

<canvas #chart baseChart
        [data]="doughnutChartData"
        [labels]="doughnutChartLabels"
        [chartType]="doughnutChartType"
        (chartClick)="chartClicked($event)"
        [colors]="chartColors">
</canvas>

Is it possible to get the value of the label from clicking the label of the doughnut chart and prevent the filter operation on the chart as well?

Upvotes: 2

Views: 4080

Answers (1)

Valentin
Valentin

Reputation: 73

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.

Upvotes: 3

Related Questions