RNdev
RNdev

Reputation: 1251

Angular: Reference current component in event listener on window

I have a component in my Angular app that has a property this.prop1, and in the constructor I add an event listener on the window object. In it I try to reference this.prop1 from the current component. So my constructor looks like this:

  constructor(private elementRef: ElementRef) {
    window.addEventListener('keydown', function(event) {
      console.log(this.prop1);
    });
  }

This throws a warning that the window object does not have a property called this.prop1, so I guess the context (the value of this) in the callback in window.

What I Want To Know:

How do I reference this.prop1 from the current component in this callback, given that the context is window?

Upvotes: 2

Views: 1048

Answers (1)

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

You can use fat arrow function like below:

You can check out this demo, maybe it'll help you!

constructor(private elementRef: ElementRef) {
   window.addEventListener('keydown', (event)=> {    
      console.log(this.prop1);
   });
}

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

Upvotes: 3

Related Questions