且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用angular2中的组件名称动态加载组件?

更新时间:2023-02-13 23:38:21

也许可行

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