ChartKick - ChartJs - 图例 onClick 覆盖默认行为

ChartKick - ChartJs - Legend onClick override with default behaviour

在我的 VueJs 应用程序中,我展示了饼图和 table 显示数据。在图例 onClick 上,我正在尝试过滤 table 行。 这是我的代码

          <pie-chart
            :donut="false"
            :data="charInfo"
            :responsive="true"
            :library="{legend:{display: true,onClick:itemSelected}}"
            legend="top"
            :colors="['#5C9AFF', '#FF3263']"/>

这里点击特定图例,'itemSelected' 被调用时有 2 个参数,第一个是 mouseEvent,第二个是 legendItem。我可以获得图例文本并可以过滤 table 行。但问题是,它会覆盖默认行为和删除图例以及禁用饼图的 hide/show 部分。在搜索时,我遇到了 ChartJs Legend onClick Issue。它说要存储原始图例 onClick 事件并从我的代码中调用它。我可以使用类似 'const original = Chart.defaults.pie.legend.onClick' 的方法存储原始的 onClick,但问题是我没有图表对象来调用 'original.call(,event,legendItem)。在这里我有点卡住了。

我在使用 ng2-charts 时四处走动尝试了一系列不同的实现来为自己解决这个问题(顺便说一句,这就是我发现这个问题的方式)。我最后添加了一个 @ViewChild 来引用我在 html.

中定义的图表

此解决方法在 ts 中需要的参考资料:

import { Component, Input, Host, OnInit, OnDestroy, ViewChild, AfterViewInit } from '@angular/core';
import { ChartsModule, BaseChartDirective } from 'ng2-charts';

添加到我的顶部 class 在 ts:

export class StatisticsComponent implements OnInit, OnDestroy {

  @ViewChild('myChart') myChart : BaseChartDirective;

使用 ng2-charts 的图表的 html 对象:

<canvas *ngIf = "loaded" 
        baseChart
        #myChart = 'base-chart'
        [datasets]="chartData"
        [colors]="chartColors"
        [chartType]="'line'"      
        [labels]="chartLabels"
        [options]="chartOptions"
        [legend]="true"
        (chartClick)="onChartClick($event)">
    </canvas>

在您随后用于覆盖图例 onClick 的方法中(我个人是在 chartOptions 中完成的)您可以添加这行代码:

this.chart.data.datasets[legendItem.datasetIndex].hidden = !this.chart.data.datasets[legendItem.datasetIndex].hidden;
this.chart.update();

这复制了图例项的标准 "onClick",因此您无需费心存储原始函数。可能很重要的一点是,在此代码中,legendItem 是 onClick 的第二个参数(第一个是事件):

function(e: any, legendItem: any)

此修复的唯一问题是默认情况下,在 ng2-charts 中,.hidden artibute 不会默认公开,因此我不得不按照此方法在模块中做一些修改: https://github.com/valor-software/ng2-charts/issues/915.

虽然我很感激你的问题与 ng2-charts 无关。我想您可能会在包装器中使用类似的方法。至少我想,在我设法解决我的问题后,我会与你分享我所做的:)