4

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.

ViqMontana
  • 5,090
  • 3
  • 19
  • 54

2 Answers2

3

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;
}
Tomasz Kasperczyk
  • 1,991
  • 3
  • 22
  • 43
2

You can use IIFE to store a component reference:

export class AppComponent {
    constructor() {
        this.componentVariable = 15;

        this.options = {
            title: {
                text: 'simple chart'
            },
            series: [{
                data: [29.9, 71.5, 106.4, 129.2],
            }],
            chart: {
                events: {
                    click: (function(component) {
                        return function(e: any) {
                            console.log(this.xAxis[0].min)
                            console.log(component.componentVariable)
                        }
                    })(this)
                }
            }
        };
    }
    options: Object;
    componentVariable: Number;
}

Live demo: https://stackblitz.com/edit/angular-highcharts-gxaf3n?file=app/app.component.ts

ppotaczek
  • 36,341
  • 2
  • 14
  • 24