0

I am working in an Angular project where I am using chart.js. I did console.log(this.myChart) three times. at line number 21 and 30 its working fine but on line number 33 it's showing undefined. why I am not able access this.myChart from onClickBar() method. how can I get clicked bar info?

import { Component, Input, OnInit } from '@angular/core';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.scss']
})
export class ChartComponent implements OnInit {

  @Input() chartData:any;
  canvas:any
  myChart:any;
  constructor() {
    
   }
   ngAfterViewInit(){
    this.canvas = document.getElementById('canvas');
    this.createChart();
    console.log(this.myChart);
    this.canvas!.onclick = this.onClickBar;
   }
 
  ngOnInit(): void {
    
  }
  createChart(){
    this.myChart = new Chart("canvas", this.chartData);
    console.log(this.myChart);
  }
  onClickBar(){
    console.log(this.myChart);
  } 
}
user1722366
  • 71
  • 1
  • 1
  • 5
  • check https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – James Sep 13 '22 at 15:23

0 Answers0