Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call typescript function inside High chart click event

MyHighChartComponent.ts

export class MyHighChartComponent {
    highchartsConfiguration: any = {
        chart: {
            events: {
                click(e) {
                    if (!($(event.target)[0].textContent)) {
                        console.log('clicked'); //this is printing
                        this.drillDown(); // how to call typescript function here?
                    }
                },
            },
        }
    };  

    drillDown() {
      console.log('drill down method called');
    }
}

How to call a typescript function from inside high charts click event?

I'm getting below error

Error Stack : TypeError: this.drillDownis not a function

like image 643
Pratap A.K Avatar asked Feb 15 '26 04:02

Pratap A.K


1 Answers

You must use an arrow function to preserve the same context (this) in the click handler.

It would look like this:

export class MyHighChartComponent {
    highchartsConfiguration: any = {
        chart: {
            events: {
                click : (e) => {
                    if (!($(event.target)[0].textContent)) {
                        console.log('clicked'); //this is printing
                        this.drillDown(); // how to call typescript function here?
                    }
                },
            },
        }
    };  

    drillDown() {
      console.log('drill down method called');
    }
}

If you need access to both the chart context and the class context you can manually save the class context in a variable (the way you'd do it before arrow functions were a thing).

class MyHighChartComponent {
  public highchartsConfig() {
    var that = this; // store this in a variable to use later
    return {
      chart: {
        events: {
          click: function(e) {
            if (!($(event.target)[0].textContent)) {
              console.log('clicked');
              // this variable now stores the chart
              // call methods on class using the that variable
              that.drillDown();
            }
          },
        },
      }
    };

  }
  public drillDown() {}
}
like image 192
toskv Avatar answered Feb 16 '26 18:02

toskv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!