示例代码:
//动态加载组件的shell组件
@Component({
selector: 'app-dynamic-host',
template: '
constructor(private componentFactoryResolver: ComponentFactoryResolver, private moduleService: DynamicLoadingService) { }
ngOnInit() { // 懒加载组件模块 this.moduleService.loadModule('path/to/your/module').then(moduleFactory => { const moduleRef = moduleFactory.create(this.dynamicHost.injector); const componentType = moduleRef.instance.someComponent; const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType); this.componentRef = this.dynamicHost.createComponent(componentFactory); }); }
ngOnDestroy() { this.componentRef.destroy(); } }
//动态加载组件的服务 @Injectable() export class DynamicLoadingService {
constructor(private compiler: Compiler) { }
public loadModule(path: string): Promise
}