0

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/

1
  • let that = this; console.log(that.testvar) not Sure but try like this. Commented Jan 19, 2021 at 7:41

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.