首页 > 解决方案 > 动态加载具有依赖项的 Angular 组件

问题描述

我一直在为小部件样式仪表板寻找一种干净的方式(不使用私有 API)解决方案。我想根据用户角色动态地将组件加载到它上面。

有没有办法动态导入组件模块中包含的组件和依赖项,并且这种解决方案生产准备好了吗?

Stackblitz 复制:

https://stackblitz.com/edit/angular-dynamically-loaded-dashboard?file=src/app/dashboard/dashboard.component.html

欢迎任何对清洁解决方案的帮助。

编辑:我尝试使用 ViewContainerRef 解析组件,虽然解决方案有效(组件被渲染),但它只是被附加到视图中,我希望能够获得具有已解决依赖项的组件的引用并将其传递给 * ngComponentOutlet 所以我可以使用 gridster 来移动和调整组件的大小。

标签: htmlangulartypescriptangular-ivy

解决方案


我认为您正在寻找的是一个ComponentFactoryResolver. 参考这个演示代码

  public render(): void {
    const index = Math.round(Math.random());
    const currentComponent = this.components[index];
    
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(currentComponent as any);

    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();

    let componentRef = viewContainerRef.createComponent(componentFactory);
  }

推荐阅读