0

I have a component. Inside I have the following:

constructor() {
  this.something = "Hello";
}

document.addEventListener('click', doSomething());

function doSomething(e) {
   console.log(this.something) // this is undefined
}

I want to make it so that I can access this.something inside of the doSomething(e). Usually I would just create a variable outside and use var self = this; then reference self.something to get to that "Hello". Unfortunately in angular 2, I am getting errors with self not being defined, etc. How can I access this.something inside of the event listener I created?

1
  • And where's that doSomething defined? Please, provide the context for the code you're posting. The snippet above will throw syntax error. Because constructor is outside of a class. Commented Apr 7, 2017 at 21:00

2 Answers 2

1

You should use lambda function to get correct this

document.addEventListener('click', () => doSomething());

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

1 Comment

It is not obvious what is the lexical scope of doSomething. It has a good chance to not get 'correct this'. The problem the question wasn't specific enough at the moment of posting, and bad questions result in bad answers.
0

Another option with Angular, instead of adding an event listener to the document directly, is the @HostListener function decorator. Below is a sample. More information.

@HostListener('click', ['$event'])
onClick(event) : void {

    event.stopPropagation();

    if(...) {
        console.log(this.something);
    }
    else if (...) {
        ...
    }
}

Obviously, I don't know your whole situation, but something like this could be of use to you.

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.