问题
Here is my codebase
export class myComponent implements OnInit {
minHist;
maxHist;
}
public callAmcharts(whichFilterType:String){
this.amchart = AmCharts.makeChart( "chart", {
"type": "serial",
"theme": "light",
"dataProvider": this.TrendData,
"valueAxes": [ {
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
}],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [ {
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "dCount",
"showHandOnHover":true
} ],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "dRange",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20,
"labelRotation": 45
},
"export": {
"enabled": true
}
});
this.amchart.addListener("clickGraphItem",this.myfunc);
}
Now onclick event myfunc
is getting called . But strangely I cant access any global variable there using this
. If its a scope
issue it should give error while calling myfunc
also right?
public myfunc(e:any){
var range= e.item.category;
let range_arr = range.split("-");
this.minHist=range_arr[0];
this.maxHist=range_arr[1];
}
I am getting error saying Uncaught TypeError: Cannot set property 'minHist' of undefined
回答1:
Change
this.amchart.addListener("clickGraphItem",this.myfunc);
to
this.amchart.addListener("clickGraphItem",this.myfunc.bind(this));
Depending on your inputs this will also work:
this.amchart.addListener("clickGraphItem",(e)=> this.myfunc(e));
which is the shorter version of:
this.amchart.addListener("clickGraphItem",(e)=> { return this.myfunc(e); });
Suggested reading: How to access the correct `this` context inside a callback?
来源:https://stackoverflow.com/questions/43447013/amcharts-click-event-in-angular-2-not-working