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);
}
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With