score:1

i'm throwing this response together piece-meal from a working solution in a module i just wrote. this particular offering hasn't been fully tested, but the crux of it is here exactly as it was working in my code. i put my final working code together using bits of code from stackoverflow, but nothing i found looks quite like this code does (using viewchild and angular click event wire-up), so my working solution is somewhat unique and imho much simpler & straightforward.

note: so long as the viewchild canvas reference becomes a chart reference at runtime, i think the code is sound. my working solution created the chart object in the typescript code where yours is created in html, so i had a direct reference to the chart object where this code attempts to use the viewchild reference.

if not, you may need to add a let statement to the event code to pull the chart object from the canvas reference (something like let mychartobj = this.mychartcanvas.(chartproperty);) and then reference mychartobj in place of this.mychart in the event code)

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


Related Query