【问题标题】:Angular read component name from json and add 'this' to the nameAngular 从 json 读取组件名称并将“this”添加到名称中
【发布时间】:2022-01-01 18:20:44
【问题描述】:

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

import { MyComponent } from './Mycomponent';

...

MyComponent = MyComponent;


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

方法:

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

用法示例:

this.test('MyComponent');

预期输出是:

this.MyComponent

当我尝试时:this.[name]

我得到了预期的标识符。

我该如何解决这个问题?

【问题讨论】:

  • 我不明白预期的结果是什么,实际的行为是什么。
  • 最好只向我们展示预期的结果而不是描述它。
  • 我输入这个:this.test('MyComponent');预期的结果是:this.MyComponent
  • 请编辑帖子。期望输出一个json,一个字符串吗?方法调用?我不知道?

标签: angular angular13


【解决方案1】:

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

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>

Here你可以检查或玩代码。

【讨论】:

  • 我得到:类型 'string' 不可分配给类型 'Type'。
  • 您能否在您的问题或帖子中添加更多信息或代码,以便于理解
  • 我已经用更多代码更新了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多