angular – 如何使用ResolveComponentFactory()但使用字符串作为键

前端之家收集整理的这篇文章主要介绍了angular – 如何使用ResolveComponentFactory()但使用字符串作为键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想做什么:

>使用类似于“resolveComponentFactory()”的东西,但使用’string’标识符来获取组件工厂.
>获得后,开始利用“createComponent(Factory)”方法.

Plnkr示例 – > enter link description here

在该示例中,您将看到“AddItem”方法

  1. addItem(componentName:string):void{
  2. let compFactory: ComponentFactory;
  3. switch(componentName){
  4. case "image":
  5. compFactory = this.compFactoryResolver.resolveComponentFactory(PictureBoxWidget);
  6. break;
  7. case "text":
  8. compFactory = this.compFactoryResolver.resolveComponentFactory(TextBoxWidget);
  9. break;
  10. }
  11.  
  12. //How can I resolve a component based on string
  13. //so I don't need to hard cost list of possible options
  14.  
  15.  
  16. this.container.createComponent(compFactory);

}

“compFactoryResolver:ComponentFactoryResolver”在构造函数中注入.

正如您将注意到的,必须对switch语句中的每个排列进行硬编码都不太理想.

当将ComponentFactoryResolver记录到控制台时,我发现它包含一个包含各种工厂的Map.

  1. CodegenComponentFactoryResolver {_parent: AppModuleInjector,_factories: Map}

但是,这张地图是私人的,无法轻易访问(据我所知).

有没有更好的解决方案然后以某种方式滚动我自己的类来访问这个工厂列表?

我看过很多关于人们试图创建动态组件的消息.但是,这些通常是在运行时创建组件.这里讨论的组件已经预先定义,我试图使用字符串作为密钥来访问工厂.

任何建议或建议都非常感谢.

非常感谢你.

它要么定义可用组件的映射,
  1. const compMap = {
  2. text: PictureBoxWidget,image: TextBoxWidget
  3. };

或者将标识符定义为将用于生成地图的静态类属性,

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

然后使用地图

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

组件类没有办法神奇地识别为字符串,因为它们没有被解析为Angular 2 DI中的字符串(自Angular 1以来已经改变了,其中所有DI单元都注释为字符串).

猜你在找的Angularjs相关文章