Angular:如何在 TS 中访问其名称作为字符串从 HTML 传递的变量

Angular: how to access in TS a variable whose name is passed from HTML as a string

我想访问 .TS 中的一个变量,其名称作为字符串从 HTML 传递。

像:

HTML:

<div id="myID"><button mat-button (click)="foo('name')">Export to Excel</button></div>

TS

varName = VARIABLE_VALUES;

foo(x: any) void {
  ...I'd like to get an access to "this.x"

}

有什么方法可以计算字符串 "this." + x 吗? 或者任何其他更优雅的方式来访问名称作为字符串传递的变量?

谢谢。

您可以使用 bracket notation,它与 Angular 或 Typescript 没有直接关系,而是一个 JavaScript 特性:

foo(x: any) void {
  // ...I'd like to get an access to "this.x"

  console.log(this[x]);
}