[英]How to get the angular component class reference inside an emitted Highcharts selection event callback function?
I guess this is a general javascript closure related problem but I am going to use specific example as I cannot wrap my head around it thinking angular-way.我想这是一个与 javascript 闭包相关的一般问题,但我将使用特定示例,因为我无法以角度方式思考它。
I have an angular component which is using Highcharts library to display a chart.我有一个角度组件,它使用 Highcharts 库来显示图表。 Highcharts can emit event when user selects part of the chart by mouse dragging.
当用户通过鼠标拖动选择图表的一部分时,Highcharts 可以发出事件。 The event provides a callback function which takes 2 arguments eg-
function(chartRef, event)
.该事件提供了一个回调函数,它接受 2 个参数,例如
function(chartRef, event)
。 I have provided the reference of a class method to the callback function.我已经为回调函数提供了一个类方法的引用。 When the event is emitted by highcharts, inside the method
this
is bound to the chartRef (callback function scope) and not the angular component class ( AppComponent
) itself.当事件由 highcharts 发出时,在方法内部
this
绑定到 chartRef(回调函数范围)而不是角度组件类( AppComponent
)本身。 How can I get a hold of the angular component class instead so that I can use the returned values by the event to my angular application?我怎样才能获得 angular 组件类,以便我可以将事件返回的值用于我的 angular 应用程序?
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
}
}
You can use IIFE to store a component reference:您可以使用IIFE来存储组件引用:
onChartSelectionEvent = (function(self) {
console.log(self)
return function(chartRef: any, chartEvent:any){
console.log(chartRef.xAxis[0].min)
console.log(chartRef.xAxis[0].max)
console.log(self)
}
// `this` is bound to the chartRef that is emmited by the Highcharts event
// How can I get a hold of the angular component class (AppComponent) instead?
//this.selection.next(chartRef.xAxis[0].max)
})(this)
Demo: https://stackblitz.com/edit/angular-kqzyjv?file=src/app/app.component.ts演示: https : //stackblitz.com/edit/angular-kqzyjv?file= src/ app/app.component.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.