html - 动态加载具有依赖项的 Angular 组件
问题描述
我一直在为小部件样式仪表板寻找一种干净的方式(不使用私有 API)解决方案。我想根据用户角色动态地将组件加载到它上面。
有没有办法动态导入组件模块中包含的组件和依赖项,并且这种解决方案生产准备好了吗?
Stackblitz 复制:
欢迎任何对清洁解决方案的帮助。
编辑:我尝试使用 ViewContainerRef 解析组件,虽然解决方案有效(组件被渲染),但它只是被附加到视图中,我希望能够获得具有已解决依赖项的组件的引用并将其传递给 * ngComponentOutlet 所以我可以使用 gridster 来移动和调整组件的大小。
解决方案
我认为您正在寻找的是一个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);
}
推荐阅读
- css - 是否可以为 onsen ui 2 添加 RTL 方向?
- android-emulator - 连续错误:PANIC:损坏的 AVD 系统路径。检查您的 ANDROID_SDK_ROOT 值 [C:\Users\NoteBook\Downloads\Compressed\sdktools]
- c# - 如何使用 SharePoint 列表选择值填充 WinForms 组合框?
- python - Pandas Melt:从列到行
- javascript - 访问对象 JavaScript
- here-api - 有没有办法更改此处地图中特定项目的 zIndex?
- c# - CsvHelper - 使用映射写入 SQL 数据库
- c# - 为什么使用 Office365 SMTP 进行身份验证声称正确的凭据无效?
- excel - 编译错误:找不到方法或数据成员 - 调用 sub
- php - 如何在不安装 ui 的情况下为 api 制作 (make: auth) Laravel 6