0

我正在尝试从 json 文件中获取组件的名称,并通过添加'this'到其名称的方法。

import { MyComponent } from './Mycomponent';

...

MyComponent = MyComponent;


data = [
    {
      "name": "MyComponent"
    }
  ];

方法:

  test(name: any) {
    return this.[name];
  }

用法示例:

this.test('MyComponent');

预期输出为:

this.MyComponent

当我尝试:this.[name]

我得到了预期的标识符。

我怎样才能解决这个问题?

4

1 回答 1

2

您正在尝试这样的事情,例如:

TS

componentName: any;

  data = [
    {
      name: 'MyComponent',
    },
  ];

  test(name: any) {
    this.componentName = `this.${name}`; // storing this.Mycomponent name to variable for displaying 
    return `this.${name}`;
  }

  testbtnHandle() {
    this.test('MyComponent');   // it will call the test function with MyComponent name parameter
  }

HTML

{{componentName}} // for display


<button type="button" (click)="testbtnHandle()">click</button>

在这里您可以检查或玩代码。

于 2021-11-23T09:25:33.380 回答