Typescript How to access component variable in foreach loop?
2 answers
If you use function (e)
, this
inside it will reference the function scope instead of the class.
Use Arrow Function
(or Fat Arrow
) instead :
x.forEach((e) => {
this.testVariable = e;
})
If there is only one parameter, you can also omit the parenthesis around it:
x.forEach(e => {
this.testVariable = e;
})
Here is a good article explaining its behavior: https://basarat.gitbooks.io/typescript/docs/arrow-functions.html
+13
source to share