[Chartjs]-Chart.js & Angular 2 โ€“ ng2-charts Custom on Click Event

11๐Ÿ‘

โœ…

Try to read DOCS

They have pretty good and understandable explanation of use.

There-are built-in 2 event handlers:

Events

chartClick: fires when click on a chart has occurred, returns information regarding active points and labels

chartHover: fires when mousemove (hover) on a chart has occurred, returns information regarding active points and labels


In code it looks like that:

 <base-chart class="chart"
            [datasets]="lineChartData"
            [labels]="lineChartLabels"
            [options]="lineChartOptions"
            [colors]="lineChartColours"
            [legend]="lineChartLegend"
            [chartType]="lineChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></base-chart>
  </div>

that chartHovered and chartClicked are your custom functions, which could has another names, and do custom things like showing modal, redirect to url etc.

19๐Ÿ‘

I found this solution at https://github.com/valor-software/ng2-charts/issues/489

public chartClicked(e: any): void {
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)
  }
 }
}

0๐Ÿ‘

 public chartClicked(e: any): void {
     console.log(e);
 }

e.active[0]._model and e.active[0]._view contain information about the part of the chart you clicked (i.e. label).

0๐Ÿ‘

I hope my answer is correct. After much searching for the only solution I found was:

public chartClicked(e:any):void {

if(e.active.length > 0){
  var points = [];
  var pointSelected = e.active[0]._chart.tooltip._model.caretY;
  var legends = e.active[0]._chart.legend.legendItems;

  for (var i = 0; i < e.active.length; ++i) {
    points.push(e.active[i]._model.y);
  }

  let position = points.indexOf(pointSelected);
  let label = legends[position].text

  console.log("Point: "+label)
}}

0๐Ÿ‘

After checking multiple places, I got it working like this for click event.

HTML:

<div class="chart">
  <canvas
    baseChart
    [data]="pieChartData"
    [type]="pieChartType"
    [options]="pieChartOptions"
    [plugins]="pieChartPlugins"
    (chartHover)="chartHovered($event)"
  >
  </canvas>
</div>

TS:

public chartHovered(e: any): void {
    if (e.event.type == "click") {
      const clickedIndex = e.active[0]?.index;
      console.log("Clicked index=" + clickedIndex);
    }
}

Ref

Leave a comment