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);
  }
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Przemysław Zamorski
  • 741
  • 2
  • 14
  • 31
  • 1
    Possible duplicate of [How to access the correct \`this\` context inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – eko Jun 01 '17 at 09:51

2 Answers2

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

borislemke
  • 8,446
  • 5
  • 41
  • 54
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);
}
Halcyon
  • 57,230
  • 10
  • 89
  • 128