如何在HighCharts中的click函数中访问外部范围变量
我正在将Angular 7和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.
这是我的活动代码:
events: {
click: function (e: any) {
console.log(this.xAxis[0].min)
console.log(this.componentVariable)
}
}
我可以访问xAxis
的值,但不能访问变量componentVariable
,因为它在上下文中不存在.我也不能bind
this
使用该函数,因为那样我将无法访问xAxis
.
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
.
如何访问click
回调函数中的两个变量?
How can I access both variables inside the callback click
function?
此处是我遇到的问题的一个简单示例.
Here is a simple example of my problem.
我对Angular不太了解,但是为了在回调中访问此属性,您必须在构造函数中创建一个辅助常量,将this
绑定到它.这是来自stackblitz的代码的修改后的版本:
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;
}