【问题标题】:Lazy loading Angular 13+ modules without the deprecated compiler在没有弃用编译器的情况下延迟加载 Angular 13+ 模块
【发布时间】:2022-11-04 23:52:34
【问题描述】:

我与loading and instantiating Angular modules 进行了广泛的合作。 (不含路由器)

但是现在使用 Angular 13,我看到了对用于实例化 NgModule 的常用编译器工具的弃用:

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

const moduleFactory = await this.compiler.compileModuleAsync(module);
const moduleRef = moduleFactory.create(this.injector);
const componentFactory = moduleRef.instance.resolveComponent(selector);

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

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

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

【问题讨论】:

    标签: angular lazy-loading lazy-initialization


    【解决方案1】:

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

    const moduleFactory = await this.compiler.compileModuleAsync(module);
    const moduleRef = moduleFactory.create(this.injector);
    

    和

    const moduleRef = createNgModule(module, this.injector);
    

    您还可以在 Angular 文档https://angular.io/guide/deprecations 中了解所有弃用和可能的替换

    【讨论】:

    • 谢谢@Yurzui!我想你在几年前设置这个问题时也帮了我一个问题!
    • createNgModuleRef 也已弃用!
    • 从 14.1 开始不推荐使用 createNgModuleRef,请改用 createNgModule
    • 这需要用于 ng 14.2.3 angular.io/api/core/createNgModule
    【解决方案2】:

    干得好 导入 ViewContainerRef、Renderer2、Injector

    创建内容元素

    const messageText = this.renderer.createText('message');
    

    创建组件引用

    const compRef = this.vcr.createComponent(<ComponentClass>, {Injector: this.injector, projectNodes: [[messageText]]});
    

    如果你想要元素

    const elem = compRef.location.nativeElement;
    

    【讨论】:

      【解决方案3】:

      不使用工厂,你必须使用ViewContainerRef.createComponent。 参考以下链接https://stackoverflow.com/a/72174262/19077843

      【讨论】:

        猜你喜欢
        • 2019-09-26
        • 1970-01-01
        • 2019-01-02
        • 2019-09-03
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多