[Chartjs]-Cannot read property 'getElementAtEvent' of undefined, Typescript

3👍

You are losing the this context if you are using a callback like that. You should wrap it in an anonymous arrow function wrapper, or use bind. Also the chart initialization is called too soon. You have to use the ngAfterViewInit lifecycle-hook to be sure that your canvas is inside the HTML:

export class TrackerPage {
  @ViewChild('doughnutCanvas') doughnutCanvas;

  doughnutChart: Chart;

  ngAfterViewInit() {

    this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {
       type: 'doughnut',
       data: {
         labels: this.titles,
         datasets: [{
           data: this.times,  
         }]
       },
       options: {
          onClick: this.timeSlotEdit.bind(this),
       }
    });
  }

  timeSlotEdit(event, array){
    let activeElement = this.doughnutChart.getElementAtEvent(event);
    console.log(activeElement);
  }
}

With an anonymous arrow function:

onClick: (event, array) => {this.timeSlotEdit(event, array)},

Another way is to keep it the way you had it before, but change the timeSlotEdit to this:

timeSlotEdit = (event, array) => {

}

this is particularly useful for unbinding events, because you can use the function reference to remove the event listener.

Leave a comment