0

I am working with a component in angular, declared a variable to hold an image, so, later will render the image in canvas context.

So, I has in the component, declared a function named Draw_Map();, it expect the "this" context to be the component.

but, when I try to call the function from inside an .onload event, like in the follow code, it is unable to find the function, obvious the context is wrong from inside an event. But, I don't know how to fix it.

so my code is:

 mapground = new Image();

...

              this.mapground.src = this.URLBackGroundPicture;
              this.mapground.onload = function() { this.Draw_Map(); } // it fails.

....

              this.Draw_Map(); // it works.

Error: Angular throw the error "Property 'Draw_Map' does not exist on type 'GlobalEventHandlers'.ts(2339)"

how to solve this problem?.

flyguille
  • 11
  • 5
  • Please refer the referred post for a canonical answer. In short you need to use arrow function to preserve the scope of `this`: `this.mapground.onload = () => this.Draw_Map()`. If you use `this` inside the `Draw_Map()` it needs to be an arrow function as well (or use `bind(this)`). – ruth Mar 29 '21 at 17:42
  • yes, it fixed the context, this.mapground.onload = () => this.Draw_Map(); learning more about arrow functions... the problem wasn't about 'this' usage, was that it didn't find the function at all. So, just the arrow function fixed both. – flyguille Mar 29 '21 at 18:26
  • It didn't find the function because it was looking inside the `onload` scope since `this` was referring to that scope. – ruth Mar 29 '21 at 19:31

0 Answers0