[Chartjs]-Angular 5 chart.js onclick returning empty array

4πŸ‘

βœ…

The below code works for me, and also it’s not required to use ElementRef to add the click event handler. You can just call a method on the (click) event of the <canvas> like below –

<canvas id="canvas" width="300" height="123" #mychart (click)="showData($event)" class="chartjs-render-monitor">{{chart}}</canvas>  

Here I have rendered the chart using the chart property of the component.

Here is the showData() method –

showData(evt:any){
  var data = this.chart.getElementsAtEvent(evt)
  console.log(data[0]._model); // it prints the value of the property
}

Here is the complete working code –

app.component.ts

import { Component,ViewChild,ElementRef,OnInit } from '@angular/core';
import Chart from 'chart.js';
declare var Chart: any;

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  implements OnInit{
  name = 'Angular 5';
  chart:any;
  // @ViewChild('mychart') el:ElementRef; 

  constructor(){

  }

  ngOnInit(){
    this.createChart();
  }
createChart(){
// var canvas = this.el; 

this.chart = new Chart('canvas', {
  type: 'bar',
  data: {
    labels: ["Browser", "Game", "Word Processing", "Database", "Spreadsheet", "Multimedia"],
    datasets: [{
      label: 'number of applications related to',
      data: [24, 10, 30, 20, 46, 78],
      backgroundColor: 'rgba(54, 162, 235, 0.2',
      borderColor: 'rgba(54, 162, 235, 1)',
      pointHoverBackgroundColor: 'red',
      borderWidth: 1
    }]
  },
  options: {
    title: {
      text: "Application Logs",
      display: true
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
})
}
    showData(evt:any){
      var data = this.chart.getElementsAtEvent(evt)
      console.log(data[0]._model);
     }

}

app.component.html

<canvas id="canvas" width="300" height="123" #mychart (click)="showData($event)" class="chartjs-render-monitor">{{chart}}</canvas>

Here is a working demo – https://stackblitz.com/edit/angular-5-example-txcthz

Leave a comment