延迟加载 Angular 13+ 模块,无需使用已弃用的编译器

Ben*_*cot 12 lazy-loading lazy-initialization angular

我在加载和实例化 Angular 模块方面进行了大量工作。(不带路由器)

但现在,在 Angular 13 中,我发现实例化 NgModule 的常用编译器工具已被弃用:

在此输入图像描述

这是我加载模块的常用代码

const moduleFactory = await this.compiler.compileModuleAsync(module);
const moduleRef = moduleFactory.create(this.injector);
const componentFactory = moduleRef.instance.resolveComponent(selector);
Run Code Online (Sandbox Code Playgroud)

更深入地了解 ViewContainerRef 现在包含工厂的 V13 更改使动态组件变得更容易了 1 步。然而,关于ViewContainerRef.createComponent()文档指出:

已弃用的 Angular 不再需要组件工厂来动态创建组件。使用不同的 createComponent 方法签名,允许直接传递 Component 类。

那么 Angular 13+ 中这些任务的新方向是什么?

yur*_*zui 19

您可以利用新的createNgModule方法并替换以下步骤:

const moduleFactory = await this.compiler.compileModuleAsync(module);
const moduleRef = moduleFactory.create(this.injector);
Run Code Online (Sandbox Code Playgroud)

const moduleRef = createNgModule(module, this.injector);
Run Code Online (Sandbox Code Playgroud)

您还可以在 Angular 文档https://angular.io/guide/deprecations中阅读有关所有弃用和可能替换的信息

  • createNgModuleRef 从 14.1 开始已弃用,请改用 createNgModule (2认同)