Angular/Typescript call a class method in an event -


i totals new ts , angular , trying build simple drawing component on canvas. have far worked way point totally don't know doing. different "this" in ts big issue me, think now. here code:

import { component, oninit } '@angular/core';  @component({     selector: 'track-creator',     templateurl: 'track-creator.component.html',     styleurls: ['track-creator.component.css'] })  export class trackcreatorcomponent implements oninit {     public canvas;     public context;      ngoninit(): void {         this.canvas = document.getelementbyid('trackcreatorcanvas');         this.context = this.canvas.getcontext("2d");          this.canvas.addeventlistener("mousedown", function (e) {             this.draw(e);         }, false);     }      draw(e): void{         this.context.beginpath();         this.context.arc(e.clientx,e.clienty,5,0,2*math.pi);         this.context.stroke();     } } 

the error here is:

error typeerror: this.draw not function

i have done reading on ts, still cant understand in situation. i'm not retarded (not @ least), don't know ts. please have in mind when try explain me error.

instead of this:

this.canvas.addeventlistener("mousedown", function (e) {     this.draw(e); }, false); 

try writing this:

this.canvas.addeventlistener("mousedown", (e) => {     this.draw(e); }, false); 

when create new function without lambda expression, this refers context of function. lambda expression preserves context of this

try going console.log(this) in first example , again in second example clearer view of means.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -