Search code examples
javascriptchart.jsangular7

can't call any function inside of onClick function chart.js


I cannot call any function inside of the onClick function of chart.js. cannot even change public variable values.

initializeGraph() {
 this.graph = new Chart('graph', {
  type: 'pie',
   data: {
    datasets: [{
     data: [1,2],
      backgroundColor: ['#RRGGBB', '#FF0000'],
     }],
      labels: ['blue','red']
    },
   options: {
    onClick : function(event,elements) {
     this.hello();
    }
   }
  });
 }

 hello() {
  console.log("i am here");
 }

Solution

  • Could you try

    initializeGraph() {
        const that = this;
        this.graph = new Chart('graph', {
            type: 'pie',
              data: {
                datasets: [{
                  data: [1,2],
                  backgroundColor: ['#RRGGBB', '#FF0000'],
                }],
                labels: ['blue','red']
              },
              options: {
               onClick : function(event,elements) {
                  that.hello();
                }
              }
         });
    

    }