在常规 JavaScript 中,我们可以向 window
全局对象添加一个名称来自字符串的属性,如下所示:
const str = "myVar";
window[str] = "Value";
console.log(myVar);
但是有没有办法在 Angular 2/4 和 Typescript 中完成类似的工作?我们可以使用 this.myVar
将常规变量存储在组件中,但是有没有一种方法可以使用字符串作为变量名来创建相同的变量?像这样的东西:
const str = "myVar";
this[str] = "Value";
// the result should be the similar as this.myVar = "Value";
最佳答案
我认为您可以使用以下内容访问并且 Typescript 接受此语法
this["myVar"]
代替
this.myVar
关于angular - 在 Angular 2+ 和 Typescript 中使用字符串作为变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46482646/