14

Hey can somebody tell me how I can access a component variable in foreach loop ? Here my Plunker

 public testVariable:number;

  test(){
    console.log('fired');
    var x  =[1,2,3,4];

    x.forEach(function (e){
      this.testVariable = e;
    })

    console.log( this.testVariable);
  }
1

2 Answers 2

33

If you use function (e), the this inside it will refer to the function's scope instead of the class.

Use the Arrow Function(or Fat Arrow) instead:

x.forEach((e) => {
    this.testVariable = e;
})

When having only 1 parameter, you may also omit the parenthesis around it:

x.forEach(e => {
    this.testVariable = e;
})

Here's a good article explaining it's behavior: https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

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

4 Comments

Won't the result of this always be 4? Also, aren't all anonymous functions "lambda"s?
@evolutionxbox you are correct, lambda is a synonym for anonymous functions, I corrected the answer. Thanks for the heads up
Exactly what I was looking for!
This was a big help. The article is no longer available, but it seems like odd behavior.
7

The value of this depends on the scope you're in. Consider doing it like this:

public testVariable:number;

test(){
    console.log('fired');
    var x  =[1,2,3,4];

    var self = this;
    x.forEach(function (e){
        self.testVariable = e;
    })

    console.log( this.testVariable);
}

1 Comment

Your implementation was necessary for es5, but is obsolete in typescript et al

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.