In regular JavaScript we can add a property to window
global object with name from string, like this:
const str = "myVar";
window[str] = "Value";
console.log(myVar);
But is there a way to do the similar job in Angular 2/4 and Typescript? We can store regular variables in component using this.myVar
, but is there a way to create the same variable using string for the variable name? Something like:
const str = "myVar";
this[str] = "Value";
// the result should be the similar as this.myVar = "Value";
I think you can access using the following & Typescript accepts this syntax
this["myVar"]
instead of
this.myVar
You can allow dynamic properties on your class:
class Test {
[key: string]: any;
constructor() {
const str = "myVar";
this[str] = "Value";
console.log(this.myVar);
}
}
But make sure you really need it because you're loosing typechecking with it:
class Test {
[key: string]: any;
constructor() {
this.teet(); // typo and therefore you will get an error in runtime
}
test() {
}
}
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