It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context.
In my Angular component, I'm using the Highcharts library to visualize data. When a user selects a part of the chart by dragging the mouse, Highcharts emits an event that triggers a callback function with 2 arguments, for example: function(chartRef, event)
. I've passed a reference to a class method as the callback function. However, when this event is triggered by Highcharts, within the method, the value of this
is bound to the chartRef (the scope of the callback function) instead of the Angular component class (AppComponent
). How can I access the Angular component class so that I can utilize the data returned by the event in my Angular application?
import { Chart } from 'angular-highcharts'
export class AppComponent {
@Output() selection = new EventEmitter<any>()
chart: Chart;
ngOnInit() {
this.init();
}
init() {
let chart = new Chart({
chart: {
zoomType: 'x',
events: {
selection: this.onChartSelectionEvent,
},
},
// code removed for brevity
this.chart = chart
)
}
onChartSelectionEvent(chartRef, event) {
console.log(chartRef.xAxis[0].min) // logs correctly
console.log(chartRef.xAxis[0].max) // logs correctly
this.selection.next(chartRef.xAxis[0].max) // doesn't work
// ERROR Error: Cannot read property 'next' of undefined
// because `this` refers to the chartRef, not the angular class
}
}