Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access outer scope variables within a click function in HighCharts

I'm using Angular 7 along with HighCharts. I'm passing a function to my high charts click event, but I also need to access some variable from the component.

Here is the code for my event:

events: {
        click: function (e: any) {
          console.log(this.xAxis[0].min)
          console.log(this.componentVariable)
        }
      } 

I can access the value of xAxis but not the variable componentVariable because it doesn't exist in the context. I cannot bind this to the function either, because then I won't have access to xAxis.

How can I access both variables inside the callback click function?

Here is a simple example of my problem.

like image 219
ViqMontana Avatar asked Sep 14 '25 19:09

ViqMontana


1 Answers

I don't know much about Angular, but in order to access this property inside the callback, you'd have to create a helper constant inside the constructor and bind this to it. Here's a modified version of your code from stackblitz:

import { Component } from '@angular/core';

@Component({
    selector: 'simple-chart-example',
    template: `
        <chart [options]="options"></chart>
    `
})

export class AppComponent {
    componentVariable: Number; //Declaring your property
    constructor() {
        const that = this; //Creating the helper constant that can be used in callbacks to refer to the AppComponent's context
        this.componentVariable = 15; //Assigning a value to your property
        this.options = {
            title: {
                text: 'simple chart'
            },
            series: [{
                data: [29.9, 71.5, 106.4, 129.2],
            }],
            chart: {
                events: {
                    click: function(e: any) {
                        console.log(this.xAxis[0].min);
                        console.log(that.componentVariable); //Using the helper constant to access your declared property
                    }
                }
            },
        };
    }
    options: Object;
}
like image 116
Tomasz Kasperczyk Avatar answered Sep 16 '25 09:09

Tomasz Kasperczyk