如何使用angular2中的组件名称动态加载组件? [英] How to load component dynamically using component name in angular2?
本文介绍了如何使用angular2中的组件名称动态加载组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在使用以下代码在应用程序中动态加载角度分量.
I am currently loading angular components dynamically in my application using following code.
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函数接受组件类型.我的问题是,有什么办法可以使用组件名称字符串加载组件,例如,我将组件定义为
Here resolveComponentFactory function accepts component type. My question is, Is there any way I can load component using component name string e.g I have component defined as
export class MyComponent{
}
如何使用组件名称字符串"MyComponent"而不是类型添加上述组件?
How can I add above component using component name string "MyComponent" instead of type?
推荐答案
也许可行
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"
where this.comp
is a string name of your Component like "MyComponent"
Plunker Example
要进行缩小处理,请参见
To do it working with minification see
这篇关于如何使用angular2中的组件名称动态加载组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文