解析类型<>来自angular2中字符串的组件

时间:2017-03-22 10:58:22

标签: angular typescript

是否可以从Type<T>值获取组件类型(string)? Smth喜欢:

let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type

2 个答案:

答案 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)

以防万一有人像我一样偶然发现这个问题。无需维护注册表是可能的。

满分为yurzui for his solution

从那里复制一份

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);