How to use ResolveComponentFactory() but with a string as a key

后端 未结 1 836
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 14:44

What I\'m trying to do:

  • Use something similar to the "resolveComponentFactory()", but with a \'string\' identifier to get Component Factories.
相关标签:
1条回答
  • 2020-12-03 15:08

    It's either defining a map of available components,

    const compMap = {
      text: PictureBoxWidget,
      image: TextBoxWidget
    };
    

    Or defining identifiers as static class property that will be used to generate a map,

    const compMap = [PictureBoxWidget, TextBoxWidget]
    .map(widget => [widget.id, widget])
    .reduce((widgets, [id, widget]) => Object.assign(widgets, { [id]: widget }), {});
    

    The map is then used like

    let compFactory: ComponentFactory;
    
    if (componentName in compMap) {
        compFactory = this.compFactoryResolver.resolveComponentFactory(compMap[componentName]);
    } else {
        throw new Error(`Unknown ${componentName} component`);
    }
    

    There's no way how component classes can be magically identified as strings, because they aren't resolved to strings in Angular 2 DI (something that was changed since Angular 1, where all DI units were annotated as strings).

    0 讨论(0)
提交回复
热议问题