ChartJS And Angular – Solution For Chart Processing Clicks/Click Event On Individual Data Segments

It is a known issue that ChartJS provides native hooks for processing clicks upon Legend items, but does not easily provide the same for a user clicking upon segments in the chart itself – slices in the pie chart, for example.

There are a plethora of solutions offered upon Stack Exchange for doing this natively in Javascript, but I wanted a better solution that primarily leverages the Angular TypeScript code instead,

I managed to create that solution, and I offer it here for the masses. See my answer here on stack overflow (carlupq) or see embedded solution below:
https://stackoverflow.com/questions/65387729/chartjs-events-in-angular/65728003#65728003

TEMPLATE

(I added #chartCanvas and (click) event)

<div style="display: block">
<canvas #chartCanvas (click)="onChartClick($event)" id="radarChart" baseChart [datasets]="radarChartData" [labels]="radarChartLabels"
    [chartType]="radarChartType" [options]="radarChartOptions"></canvas>

 COMPONENT CODE

Add to your imports:

import { Chart, ChartElement } from 'chart.js';

Add to your class variables:

@ViewChild('chartCanvas') myChart;

Your event handler:

onChartClick(event) {
  let ActivePoints: ChartElement[] = this.myChart.getElementsAtEvent(event);
  // to do - check ActivePoints for undefined, return if true
  let idx = ActivePoints[0]['_index'];
  let lbl: string = this.myChart.data.labels[idx];
  let dat = this.myChart.data.datasets[0].data[idx];
  console.log(lbl,dat);
}
This entry was posted in Uncategorized and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s