Resolve Type<> of component from string in angular2

后端 未结 2 368
谎友^
谎友^ 2020-12-09 12:39

Is it possible to get type of component (Type) from string value? Smth like:

let typeStr: string = \'MyComponent\';
let ty         


        
2条回答
  •  半阙折子戏
    2020-12-09 13:25

    You can't do that without maintaining a "registry" for your classes.

    interface Component { }
    
    type ComponentClass = { new (): Component };
    
    const REGISTRY = new Map();
    
    function getTypeFor(name: string): ComponentClass {
        return REGISTRY.get(name);
    }
    

    As for how to add entries to this REGISTRY, you have a few options, here are two:

    (1) Manually add it after every class definition:

    class ComponentA implements Component { ... }
    REGISTRY.set("ComponentA", ComponentA);
    

    Or make a function for it:

    function register(cls: ComponentClass): void {
        REGISTRY.set(cls.name, cls);
    }
    
    class ComponentA implements Component { ... }
    register(ComponentA);
    

    (2) Use a decorator:
    Just use the above register function as a decorator:

    @register
    class ComponentA implements Component { ... }
    

提交回复
热议问题