将组件从其名称实例化为字符串

将组件从其名称实例化为字符串

本文介绍了Angular 5 - 将组件从其名称实例化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用 ComponentFactoryResolver.resolveComponentFactory(AComponentType)

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

but the method expects a Type, while in my code I have the name of the type as a string.

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

In the Angular API is there a method to resolve by string?If not, how can I convert a string to a Type in TypeScript?

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

In case that none of the above is possible I will resort to a map but it's not so straightforward as the components I need to instantiate will come from remotely fetched UMD angular component library.

推荐答案

您可以执行以下操作:

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

然后:

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

这篇关于Angular 5 - 将组件从其名称实例化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:07