如何在Angular其他模块中使用AppModule声明的PopupNotification组件?
调整方案
Angular中可复用的公共组件需要在所属模块完成声明+导出,使用方导入对应模块后才能正常调用,按以下步骤修改即可:
1. 调整PopupNotificationModule配置
将PopupNotificationComponent从AppModule迁移到专属的通知模块中声明,同时新增exports配置暴露组件给外部使用:
@NgModule({ declarations: [ PopupNotificationComponent // 组件仅可在一个模块声明,迁移到此处 ], imports: [ CommonModule, TranslateModule.forChild(), ], exports: [ PopupNotificationComponent // 导出组件,外部模块导入后可直接调用 ] }) export class PopupNotificationModule { }
2. 清理AppModule冗余配置
移除AppModule中重复声明的弹窗组件:
@NgModule({ declarations: [ AppComponent // 删除原有的PopupNotificationComponent声明,避免重复声明报错 ], imports: [ PopupNotificationModule, // 若CarModule为路由懒加载,无需在此处导入;若为直接注册则保留CarModule导入 ], }) export class AppModule { }
3. CarModule导入通知模块
在需要使用弹窗的业务模块中导入PopupNotificationModule,模块下的所有组件即可正常调用弹窗组件、绑定@Input字段:
@NgModule({ declarations: [ CarListComponent, ], imports: [ PopupNotificationModule // 导入公共弹窗模块 ], }) export class CarModule { }
- 所有Angular组件仅可在一个NgModule中声明,不可重复声明
- 弹窗组件用到的依赖(比如翻译管道、公共指令等)只要在PopupNotificationModule中完成导入,外部调用时无需重复导入依赖
内容的提问来源于stack exchange,提问作者Catalin Sasu
相关产品推荐
相关产品推荐

