Reputation: 737
I'm working currently with some charts from charts.js, i'm adding some simple interaction with them, when the user clicks a bar from a bar chart, a variable saves which bar was clicked.
This variable updates a line chart, this chart is updated with data previously saved in an array, so everytime the user clicks a different bar from the bar chart, the line chart should change.
My problem is that the variable doesn't change i get two different values. By default the variable is initialized in 0.
Console log output:
from barchart click:3
from change function:0
from barchart click:2
from change function:0
I print these lines from 2 different functions that happen at the same time.
This is function that should change the variable value when the bar chart is clicked on a bar.
graphClickEvent(event:any, array:any){
if(array[0]){
this.offsetGraficas = array[0]._index;
console.log("from barchart click:"+this.offsetGraficas);
}
}
and this other function that happens at the same time:
changeHistorico(n:number) {
console.log("from change function:"+this.offsetGraficas);
this.show_historico = true;
//some unrelated code goes here
}
from what i see, graphClickEvent is executed first, but i don't se any change in the variable. Why it doesn't work as intended?
Upvotes: 4
Views: 481
Reputation: 21
Yes, the this
from within a click event is different from the this
of the parent component.
Global variable is a way.
But a better solution would be to pass the component instance is the config of the chart.js graph.
this.dsChart2 = new Chart(myCtx2,{
type: 'pie',
parentInstance: this,
data: { ... }
options:{
onClick: this.graphClickEvent
}
}
Now when the graphClickEvent
is called, you get two values, event and the chart Instance, from which you are already getting the index value.
So now from within the click event function, you can reference the parentInstance
, as follows:
graphClickEvent(evt,item) {
console.dir(item);
let parentThis = item[0]['_chart']['config']['parentInstance'];
// here parentThis is the component this or $scope
parentThis.variable = value;
}
Upvotes: 2
Reputation: 17899
Looks like "this" in graphClickEvent and "this" in changeHistorico are different this.
Upvotes: 2