首页 > 解决方案 > 图表点击事件 - 点击圆环图的标签,不返回标签 ng2-charts

问题描述

我有一个圆环图设置,我想在标签上使用点击事件。使用此答案中的代码(https://stackoverflow.com/a/49118430/4611941),我可以在单击图表以返回标签和数据时触发单击事件:

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)
        }
    }
}

当返回标签时单击图表数据本身时,这非常有效,然后我可以使用此值。但是,当单击图表上方的标签本身时,此代码无法获取单击的标签的值(e.active.lenth = 0)。但是,它仍然通过将该标签的数据删除/添加到圆环图来执行过滤。

这就是我目前的图表设置方式:

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

是否可以通过单击圆环图的标签来获取标签的值并防止对图表进行过滤操作?

标签: angularchart.jsng2-charts

解决方案


您可以通过@ViewChild 访问您的图表。您已经在 HTML 中设置了本地引用。

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

这个包含图例中的标签。

如果您在画布元素中传递一些选项,那么您也可以操纵 onClick 行为。

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

在您的 .ts 文件中,您创建包含 onClick 行为的 chartOptions。这将覆盖默认行为。例如,您可以使用其索引来总结特定标签的值。

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

不要忘记导入

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

这是修改后的代码。 希望对您有所帮助。


推荐阅读