【问题标题】:How to transform a String into a Type / Component in Angular?如何在 Angular 中将字符串转换为类型/组件?
【发布时间】:2019-05-27 18:45:52
【问题描述】:

在 Angular 中,我得到一个字符串并希望将其转换为类型/组件。例如,我得到“ListComponent”并想向应用程序添加一个 ListComponent。 我不想将这些映射到地图或其他东西中。是否可以从字符串中获取类型?

stringComponent = "ListComponent";
typeComponent = *transform "ListComponent" to ListComponent;
method(typeComponent);

【问题讨论】:

  • 组件是否存在于您的模板中?
  • I dont want to map these in an Map 好吧,你被卡住了,不是吗。这个问题在这里被问过很多次,答案都是一样的。 Angular API 中的任何地方都没有组件工厂的 string 表示。组件工厂有一个字符串选择器,但无法获取所有工厂的数组,因为它们绑定到模块。模块是一个层次结构,但无法从应用程序引用中获取子模块。所以你被卡住了。
  • @vsarunov 是的,它存在。
  • @cgTag 好的,是的,我搜索了它,但找不到任何解决方案.. 感谢您的回答。

标签: angular typescript components


【解决方案1】:

可能是这样的:

class ListComponent {
  foo = 'bar'
}
class LolComponent {}

const componentsMap = {
  ListComponent,
  LolComponent
}

type ComponentName = keyof typeof componentsMap;


function convertStringToComponent<Name extends ComponentName>(name: Name): (typeof componentsMap)[Name] {
  return componentsMap[name];
}

const CompByName = convertStringToComponent('ListComponent');

const instance = new CompByName();

instance.foo; // ok!

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多