[英]How to transform a String into a Type / Component in Angular?
In Angular, i get a String and want to transform it to a Type / Component. 在Angular中,我得到一个String,并希望将其转换为Type / Component。 For example, i get "ListComponent" and want to add a ListComponent to the Application. 例如,我得到“ListComponent”并想要将ListComponent添加到Application。 I dont want to map these in an Map or something. 我不想在地图或其他东西中映射这些。 Is it possible to get the Type out of a String? 是否可以从字符串中获取Type?
stringComponent = "ListComponent";
typeComponent = *transform "ListComponent" to ListComponent;
method(typeComponent);
Maybe something like: 也许是这样的:
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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.