是否可以从Type<T>
值获取组件类型(string
)? Smth喜欢:
let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type
答案 0 :(得分:6)
如果没有为您的课程维护“注册表”,则无法做到这一点。
interface Component { }
type ComponentClass = { new (): Component };
const REGISTRY = new Map<string, ComponentClass>();
function getTypeFor(name: string): ComponentClass {
return REGISTRY.get(name);
}
至于如何向此REGISTRY
添加条目,您有几个选项,这里有两个:
(1)在每个类定义后手动添加它:
class ComponentA implements Component { ... }
REGISTRY.set("ComponentA", ComponentA);
或者为它做一个功能:
function register(cls: ComponentClass): void {
REGISTRY.set(cls.name, cls);
}
class ComponentA implements Component { ... }
register(ComponentA);
(2)使用装饰者:
只需使用上面的register
函数作为装饰器:
@register
class ComponentA implements Component { ... }
答案 1 :(得分:0)
以防万一有人像我一样偶然发现这个问题。无需维护注册表是可能的。
从那里复制一份
import { Type } from '@angular/core';
@Input() comp: string;
...
const factories = Array.from(this.resolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);