[英]Dynamically load Angular component with dependencies
我一直在為小部件樣式儀表板尋找一種干凈的方式(不使用私有 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);
}
我已經設法解決它:缺少的鏈接是 ngModuleFactory 部分:
<ng-container
*ngComponentOutlet="widget.component; ngModuleFactory: widget.module"
></ng-container>
在 widget.service.ts 我已經解決了模塊:
const { TasksWidgetModule } = await import('../tasks-widget/tasks-widget.module');
module = await this.compiler.compileModuleAsync(TasksWidgetModule);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.