Reputation: 536
I have a click function on an OpenLayers map
testvar: string
map = new Map()
ngOnInit(): void {
this.map.on('click', function(event) {
console.log(this.testvar)
})
}
But this
is not available within the scope of the click function.
Any ideas how to do this/
Upvotes: 0
Views: 198
Reputation: 1805
this is because you declare your function using the function
keyword.
If you declare you function as an arrow function, it will work:
this.map.on('click', event => {
console.log(this.testvar)
})
Take a look at this article for more detail about arrow function vs function: https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/
or this one: https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/
Upvotes: 1