我目前正在使用以下代码在我的应用程序中动态加载 Angular 组件。
export class WizardTabContentContainer {
@ViewChild('target', { read: ViewContainerRef }) target: any;
@Input() TabContent: any | string;
cmpRef: ComponentRef<any>;
private isViewInitialized: boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {
}
updateComponent() {
if (!this.isViewInitialized) {
return;
}
if (this.cmpRef) {
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.TabContent);
this.cmpRef = this.target.createComponent(factory);
}
}
这里 resolveComponentFactory 函数接受组件类型。我的问题是,有什么方法可以使用组件名称字符串加载组件,例如我将组件定义为
export class MyComponent{
}
如何使用组件名称字符串“MyComponent”而不是类型添加上述组件?
最佳答案
也许这会奏效
import { Type } from '@angular/core';
@Input() comp: string;
...
const factories = Array.from(this.resolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);
其中 this.comp
是您的组件的字符串名称,例如 "MyComponent"
要做到这一点,请参阅缩小
关于angular - 如何在angular2中使用组件名称动态加载组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40115072/