Angular 5-将组件的名称实例化为字符串 [英] Angular 5 - instantiate a component from its name as a string

查看:95
本文介绍了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-将组件的名称实例化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆