Angular中无法同时动态加载多组件的问题求助
问题根源
你的loadComponent方法中调用了viewContainerRef.clear(),这会清空当前容器内所有已加载的组件,导致每次点击按钮都会替换掉之前的组件,无法同时显示两个。
解决方案
方案1:使用两个独立的动态加载容器
适合需要将两个组件放在不同位置的场景。
- 修改模板:添加两个
DynamicLoadDirective实例(可通过模板引用变量区分)
<!-- 第一个容器:加载Solarwinds组件 --> <ng-template #solarContainer dynamicLoad></ng-template> <!-- 第二个容器:加载PeriodicalCheck组件 --> <ng-template #periodicalContainer dynamicLoad></ng-template>
- 修改header.component.ts:获取两个独立的容器引用
@ViewChild('solarContainer', {static: true}) solarContainer: DynamicLoadDirective; @ViewChild('periodicalContainer', {static: true}) periodicalContainer: DynamicLoadDirective; loadSolarwindsComponent() { this.dynamicLoadService.loadComponent( ComponentLoad.SolarwindsPanelComponent, this.solarContainer.viewContainerRef ); } loadPeriodicalCheckComponent() { this.dynamicLoadService.loadComponent( ComponentLoad.PeriodicalCheckPanelComponent, this.periodicalContainer.viewContainerRef ); }
- 可选调整:如果需要每次点击对应按钮时重置该容器的组件,可以保留服务中的
viewContainerRef.clear();如果不需要重置,可移除该语句。
方案2:在同一个容器中加载多个组件
适合将两个组件放在同一容器内(如堆叠显示)。
直接修改dynamic-load.service.ts,移除清空容器的语句:
async loadComponent(component: ComponentLoad, viewContainerRef: ViewContainerRef) { let _component: any = null; switch (component) { case ComponentLoad.SolarwindsPanelComponent: _component = (await import("../../dialogs/notification/solarwinds/solarwinds-panel/solarwinds-panel.component")).SolarwindsPanelComponent; break; case ComponentLoad.PeriodicalCheckPanelComponent: _component = (await import("../../dialogs/periodicalCheck/periodical-check-panel/periodical-check-panel.component")).PeriodicalCheckPanelComponent; break; } // 移除clear(),保留已加载的组件 // viewContainerRef.clear(); return viewContainerRef.createComponent(_component); }
这样每次点击按钮都会在同一个容器内新增组件,两个组件会同时存在。注意调整组件的CSS样式,避免布局混乱。
内容的提问来源于stack exchange,提问作者Resul Sarı
相关产品推荐
相关产品推荐

