Angular 5 - instantiate a component from its name as a string

前端 未结 2 879
北荒
北荒 2021-01-17 21:33

I know how to init components using ComponentFactoryResolver.resolveComponentFactory(AComponentType)

but the method expects a Type, while i

相关标签:
2条回答
  • 2021-01-17 21:59

    I had the same problem, where i need to use a string to select what component to build. After some digging I created a list of the components that is added to the NgModuleexport and entryComponents lists.

    template-components.ts

    export const TEMPLATE_COMPONENTS: Type<any>[] = [
        Temp1Component,
        Temp2Component
      ]
    

    in my NgModule class I just add TEMPLATE_COMPONENTS to both exports and entryComponents

    In the component with the ComponentFactoryResolver you generate a list of Types, with the same string as a key.

    let templateTypes: { [name: string]: Type<{}> } = 
        TEMPLATE_COMPONENTS.reduce((p, c) => { p[c.name] = c; return p }, {})
    
    // templateTypes = {'Temp1Component':Temp1Component,...}
    
    this.componentFactoryResolver.resolveComponentFactory(templateTypes[string]);
    

    This means that you only have to add the components to one place, simplifying adding more components.

    Its probably possible to skip the whole TEMPLATE_COMPONENTSin a separate list step and get the list directly from the NgModuleclass, but that will be sometime in the future.

    0 讨论(0)
  • 2021-01-17 22:14

    You can do the following:

    const classesMap = {
      AComponentType: AComponentType,
      BComponentType: BComponentType
    }
    

    And then:

    CreateDynamicComponent(typeName: string) {
        ...
        const componentFactory = ComponentFactoryResolver.resolveComponentFactory(classesMap[typeName].prototype.constructor)
        ...
    }
    
    0 讨论(0)
提交回复
热议问题