Search code examples
angulareval

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


I want to access a variable in the .TS whose name is passed from HTML as a string.

Smth like:

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"

}

is there any way to evaluate the string "this." + x? or any other more elegant way to get an access to the variable whose name is passed as a string?

Thanks.


Solution

  • You can use the bracket notation which is not directly related to Angular or Typescript but rather a JavaScript feature:

    foo(x: any) void {
      // ...I'd like to get an access to "this.x"
    
      console.log(this[x]);
    }