我试图弄清楚如何在运行时从字符串获取对 Angular 2+ (Angular 5) 中的类的引用。我尝试了示例on this page 。这个对我不起作用:
console.log((<any>Object).create(window[className])); // undefined
其他人正在使用导入,我试图避免这种情况。
我没有使用命名空间,但不知道 Angular 是否有自己的命名空间。我尝试窥探窗口对象,看看是否能找到任何东西。我找到的只是 getAllAngularRootElements、getAllAngularTestabilities 和 getAngularTestability,但这些似乎不是我想要的。
最佳答案
我曾经有过类似的需求,需要动态渲染组件,并且只有一个对需要注入(inject)到页面中的类的字符串引用(动态仪表板类型的应用程序)。我最终做了以下事情:
- 创建服务以通过字符串名称保存组件的引用
- 将服务注入(inject)模块组件并注册该组件
- 将服务注入(inject)到需要通过字符串名称获取组件的组件中
这大致就是我所拥有的服务(该类负责实际创建动态组件,而不是像下面那样获取引用):
export class DynamicComponentService {
private dynamicComponentTypes: { [type: string]: Type<BaseInterfaceSectionComponent> } = {};
registerDynamicComponentTypes(...dynamicComponentTypesToRegister: { component: Type<BaseInterfaceSectionComponent>, name: string }[]) {
dynamicComponentTypesToRegister.forEach(dynamicComponentType => {
this.dynamicComponentTypes[dynamicComponentType.name] = dynamicComponentType.component;
});
}
getDynamicComponentType(name: string): Type<BaseInterfaceSectionComponent> {
return this.dynamicComponentTypes[name];
}
}
在这样做之前我并不知道,但实际上您可以将依赖项注入(inject)模块的构造函数中。我利用这个功能来使用服务来注册动态组件:
export class BarChartContentModule {
constructor(dynamicComponentService: DynamicComponentService) {
const dynamicComponent = { component: BarChartContentComponent, name: 'BarChartContentComponent' };
dynamicComponentService.registerDynamicComponentTypes(dynamicComponent);
}
}
不确定这是否是您正在寻找的内容,但我想我会分享。
关于javascript - Angular/ typescript : How to get a reference to a class from a string at runtime without importing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49661825/