可以使用Angular中的ComponentFactoryResolver来实现从懒加载模块中动态加载组件。首先需要在要加载的组件所属的懒加载模块中定义对应的Component,然后使用ComponentFactoryResolver来创建和获取该组件的实例。
例如,我们需要从一个名为"lazy.module.ts"的懒加载模块中动态加载一个名为"LazyComponent"的组件。首先,在"lazy.module.ts"中定义LazyComponent:
import {Component} from '@angular/core';
@Component({
selector: 'lazy-component',
template: `Lazy Component
`
})
export class LazyComponent {}
然后,在要使用懒加载组件的组件中,引入ComponentFactoryResolver并注入进来,使用resolveComponentFactory方法创建和获取"LazyComponent"的实例:
import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver} from '@angular/core';
@Component({
selector: 'app-root',
template: `App Component
`
})
export class AppComponent {
@ViewChild('lazyComponentContainer', {read: ViewContainerRef}) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
async loadComponent() {
const lazyModule = await import('./lazy.module');
const lazyComponent = lazyModule.LazyComponent;
const factory = this.resolver.resolveComponentFactory(lazyComponent);
const componentRef = this.container.createComponent(factory);
}
}
其中,使用import动态加载懒加载模块,然后使用resolveComponentFactory创建并返回一个ComponentFactory,最后使用createComponent方法在ViewContainerRef的容器中创建"LazyComponent"的实例。最终的效果就是在"app-root"组件中动态加载了“LazyComponent”组件。