1👍
✅
ngAfterViewInit() {
console.log('A', this.myVariable)
this.canvas.onmousemove = function(e) {
console.log('onMouseMove', this.myVariable)
}
}
If I understand your example correctly, you get an output of
A myValue
onMouseMove undefined
but you would like to have onMouseMove myValue
as well.
You can simply store a reference to this
while it’s still available, and use it in your onmousemove()
handler later
ngAfterViewInit() {
const self = this
console.log('A', self.myVariable)
this.canvas.onmousemove = function(e) {
console.log('onMouseMove', self.myVariable)
}
}
which should output
A myValue
onMouseMove myValue
0👍
A function
has its own this
context, so calling this
inside of the function body accesses the function rather than the component. An arrow function does not establish a this
scope, so you can access the component as this
from inside of an arrow function.
this.canvas.onmousemove = (e) => {
this.myVariable = true;
console.log(this.myVariable);
};
Source:stackexchange.com