Resolve Type<> of component from string in angular2

后端 未结 2 369
谎友^
谎友^ 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:21

    Just in case anyone stumbles across this question like me. It is possible without maintaining a registry.

    Full credit goes to yurzui for his solution.

    Just a copy from there:

    import { Type } from '@angular/core';
    
    @Input() comp: string;
    ...
    const factories = Array.from(this.resolver['_factories'].keys());
    const factoryClass = >factories.find((x: any) => x.name === this.comp);
    const factory = this.resolver.resolveComponentFactory(factoryClass);
    const compRef = this.vcRef.createComponent(factory);
    

提交回复
热议问题