Angular 15如何更新从懒加载模块动态加载组件的旧代码?
在Angular 15中从懒加载模块动态加载组件的替代方案
Angular 15弃用了ComponentFactoryResolver和ViewContainerRef.createComponent的旧签名,你可以改用直接传入组件类型的新API实现相同功能,代码简化如下:
async onModalOpenButtonClick(modalname: string) { // 懒加载目标模块与组件 const { BasicModalsModule } = await import('../../modals/basic/basic-modals.module'); const { ModalLaunchComponent } = await import('../../modals/basic/modal-launch/modal-launch.component'); // 创建懒加载模块的引用 const moduleFactory = await this.compiler.compileModuleAsync(BasicModalsModule); const moduleRef = moduleFactory.create(this.injector); // 直接使用组件类型创建实例,指定模块引用以继承模块依赖 const componentRef = this.vcr.createComponent(ModalLaunchComponent, { injector: this.injector, ngModuleRef: moduleRef }); // 调用组件实例方法 componentRef.instance.openModal(modalname); }
关键变更说明:
- 移除
componentFactoryResolver.resolveComponentFactory调用:Angular 14+的ViewContainerRef.createComponent支持直接传入组件类,无需手动创建组件工厂 - 使用对象形式配置参数:新签名通过配置对象传递
injector、ngModuleRef等参数,代码结构更清晰 - 保留模块引用创建:确保动态加载的组件能访问懒加载模块中声明的服务、指令等依赖
如果你的ModalLaunchComponent是独立组件(Angular 14+特性),可进一步简化,无需加载模块:
async onModalOpenButtonClick(modalname: string) { const { ModalLaunchComponent } = await import('../../modals/basic/modal-launch/modal-launch.component'); const componentRef = this.vcr.createComponent(ModalLaunchComponent, { injector: this.injector }); componentRef.instance.openModal(modalname); }
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

