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

偶尔善良 提交于 2020-01-16 04:09:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/59067910/chart-click-event-clicking-label-of-doughnut-chart-doesnt-return-label-ng2-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!