Chartjs-Ng2-charts โ€“ Highlighting a series when hovering over the corresponding legend label

0๐Ÿ‘

โœ…

  1. You need the options.plugins.legend.onHover callback function to capture the event when the legend has hovered.

  2. To highlight the bar elements, you need to call the setActiveElements method and provide items of ActivePoints[]. The key point is the ActivePoints items must with the datasetIndex which is the currently selected legend item index (legendItem.datasetIndex) and index for each item index in the dataset. Reference: Programmatic Event Triggers

import { Chart, ChartConfiguration, LegendItem } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

@ViewChild(BaseChartDirective) baseChart!: BaseChartDirective;

ngAfterViewInit() {
  this.barChartOptions = {
    ...this.barChartOptions,
    plugins: {
      legend: {
        onHover: (evt, legendItem: LegendItem) => {
          this.baseChart?.chart?.setActiveElements(
            this.baseChart!.chart!.getDatasetMeta(
              legendItem.datasetIndex!
            ).data!.map((x, i) => ({
              datasetIndex: legendItem.datasetIndex!,
              index: i,
            }))
          );

          this.baseChart.update();
        },
      },
    },
  };
}

Demo @ StackBlitz

Leave a comment