simdevmon simdevmon - 3 years ago 82
TypeScript Question

How to access different contexts of 'this' in HighCharts callback (Angular / Typescript)

I am using HighCharts within an Angular / Typescript project. Generally it works fine, but now I got stuck:

When clicking on a point I want to get more information about that point from an http service. HighCharts provides the possibility to add a callback function: http://api.highcharts.com/highstock/plotOptions.series.point.events.click

The problem is that I need information about the point (the point information is bind to 'this'), but also invoke the service where 'this' refers to the class instance.

@Component({
// ...
})
export class ChartComponent {

chart: any;

constructor(private dataService: DataService) { }

onPointClick(point: any) {
this.dataService.getPointDetails(point) // then ...
}

buildDataChart() {
let Highcharts = require('highcharts/highstock');
this.chart = new Highcharts.StockChart({
// ...
plotOptions: {
series: {
point: {
events: {
click: // How to implement this function?
}
}
}
}
});
}
}


I tried different things without success:

click: function() {
console.log('Point information ' + this.x + ' ' + this.y);
// outside of Angular scope and service cannot be reached.
}


With this I am also outside of Angular scope

click: this.onPointClick


Now I am inside Angular scope, but have no access to point information:

click: this.onPointClick.bind(this)


Here I am also inside Angular scope, but have no access to point information:

click: () => this.onPointClick(this)


Does anybody know how I can take the point information and invoke the service with this? The only thing I can think of right now would be some global dom-elements, but this does not seem very nice.

Answer Source

You should use the event parameter send through the click event and define your handler (onPointClick) as a field value of your component class. No need for bind or weird this context this way. Within the event the point is defined at event.point:

export class ChartComponent {

    chart: any;

    constructor(private dataService: DataService) {    }

    onPointClick = (event: any) => {
        this.dataService.getPointDetails(event.point);
    };

    buildDataChart() {
        let Highcharts = require('highcharts/highstock');
        this.chart = new Highcharts.StockChart({
             plotOptions: {
                series: {
                    point: {
                        events: {
                            click: this.onPointClick
                        }
                    }
                }
            }
        });
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download