如何在Angular中将字符串转换为类型/组件?

时间:2019-05-26 13:33:51

标签: angular typescript components

在Angular中,我得到一个String并想将其转换为Type / Component。例如,我得到“ ListComponent”并想将ListComponent添加到应用程序中。 我不想将它们映射到Map或其他内容中。是否可以从字符串中获取类型?

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

1 个答案:

答案 0 :(得分:0)

也许像这样:

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!