【问题标题】:Angular 5 - instantiate a component from its name as a stringAngular 5 - 将组件的名称实例化为字符串
【发布时间】:2018-08-16 12:27:12
【问题描述】:

我知道如何使用ComponentFactoryResolver.resolveComponentFactory(AComponentType) 初始化组件

但该方法需要Type,而在我的代码中,我将类型的名称命名为string

在 Angular API 中是否有通过string 解析的方法? 如果没有,如何在 TypeScript 中将字符串转换为 Type

如果以上都不可能,我将求助于地图,但这并不那么简单,因为我需要实例化的组件将来自远程获取的 UMD 角度组件库。

【问题讨论】:

标签: angular typescript components angular5 umd


【解决方案1】:

您可以执行以下操作:

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

然后:

CreateDynamicComponent(typeName: string) {
    ...
    const componentFactory = ComponentFactoryResolver.resolveComponentFactory(classesMap[typeName].prototype.constructor)
    ...
}

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,我需要使用字符串来选择要构建的组件。经过一番挖掘,我创建了一个添加到 NgModuleexport 和 entryComponents 列表中的组件列表。

    模板组件.ts

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

    在我的 NgModule 类中,我只需将 TEMPLATE_COMPONENTS 添加到 exportsentryComponents

    在带有ComponentFactoryResolver 的组件中,您生成一个类型列表,其字符串与键相同。

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

    这意味着您只需将组件添加到一个位置,从而简化了添加更多组件的过程。

    可能在单独的列表步骤中跳过整个TEMPLATE_COMPONENTS,直接从NgModuleclass 中获取列表,但这将是将来的某个时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      相关资源
      最近更新 更多