Angular 5懒加载子模块复用主应用组件报错求助
解决Angular组件重复声明错误:Type AccountInfoComponent is part of the declarations of 2 modules
这个错误我太熟了!Angular的核心规则就是一个组件只能归属于一个NgModule的declarations数组,你现在把AccountInfoComponent同时放在了主AppModule和ChildModule里,所以直接触发了这个报错。要复用组件,正确的姿势是用共享模块,下面给你一步步来:
步骤1:创建共享模块(SharedModule)
首先在你的app目录下新建一个shared文件夹,里面创建shared.module.ts文件,把AccountInfoComponent移到这里来统一管理:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; // 如果组件用到了ngIf、ngFor这类指令,必须导入 import { AccountInfoComponent } from '../components/accountInfo/accountInfo.component'; @NgModule({ declarations: [ AccountInfoComponent // 在这里声明组件 ], imports: [ CommonModule // 共享模块里要导入通用模块,避免使用方重复导入 ], exports: [ AccountInfoComponent // 关键!把组件导出,这样其他模块导入共享模块后就能用它 ] }) export class SharedModule { }
步骤2:清理原有模块的重复声明
- 打开你的
AppModule,找到declarations数组,把AccountInfoComponent删掉,然后在imports数组里加入SharedModule - 同样处理
ChildModule:移除declarations里的AccountInfoComponent,在imports里加入SharedModule
举个AppModule的修改示例:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { SharedModule } from './shared/shared.module'; // 导入共享模块 import { AppComponent } from './app.component'; import { UserComponent } from './components/user/user.component'; @NgModule({ declarations: [ AppComponent, UserComponent // 这里只保留属于AppModule的组件 ], imports: [ BrowserModule, SharedModule // 加入共享模块,就能用AccountInfoComponent了 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
步骤3:正常复用组件
现在不管是在主应用的模板(比如app.component.html)还是ChildComponent的模板里,都可以直接使用<app-account-info>标签,完全没问题啦!
额外注意点
- 以后如果还有需要跨模块复用的组件、管道、指令,都可以放到SharedModule里,统一管理
- 共享模块里导入的CommonModule一定要exports出去,这样使用共享模块的模块就不用再单独导入CommonModule了
内容的提问来源于stack exchange,提问作者j-p
相关产品推荐
相关产品推荐

