Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?
生活随笔
收集整理的這篇文章主要介紹了
Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有一天,我寫了一個自信滿滿的自定義組件myComponent,在多個頁面import使用了,結果控制臺給我來這個
我特么褲子都脫了,你給我來這個提示是幾個意思
仔細一看 The Component 'MyComponentComponent' is declared by more than one NgModule
什么鬼?說我的組件被多個模塊使用?搞什么飛機,我就是要多個頁面使用呀!!!
通常出現上面這種報錯都是因為使用了懶加載路由(類似下面的)
const routes: Routes = [...{path: 'first',loadChildren: () => import('./com/first/first.module').then(m => m.FirstModule),//異步加載、惰性加載、懶加載}, ...]
于是乎查閱官方文檔發現一個shared.module.ts的東東
首先找一個干凈的文件夾創建一個
shared.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MyComponentComponent } from 'src/app/my-component/my-component.component';// 這里加入自定義公共組件----------------------------------------
let declarations = [MyComponentComponent,
];@NgModule({imports: [CommonModule,], //公共組件依賴的第三方組件可以在此處引入declarations,exports: declarations,
})
export class SharedModule { }
去需要使用相關公共組件的頁面Module文件里面
first.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { FirstComponent } from './first.component';@NgModule({imports: [SharedModule,//這里引入公共組件模塊(共享特性模塊)RouterModule.forChild([{ path: '', component: FirstComponent }]),//這句不加不會生效],declarations: [FirstComponent,]
})
export class FirstModule { }
first.component.html
first
<app-my-component></app-my-component>
second.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { SecondComponent } from './second.component';@NgModule({imports: [SharedModule,//這里引入公共組件模塊(共享特性模塊)RouterModule.forChild([{ path: '', component: SecondComponent }]),//這句不加不會生效],declarations: [SecondComponent,]
})
export class SecondModule { }
second.component.html
second
<app-my-component></app-my-component>
my-component.component.html
<h1>我特么終于沒報錯啦!</h1>
?路由自己配置好,直接訪問http://localhost:4200/first
訪問http://localhost:4200/second
?
?
總結
以上是生活随笔為你收集整理的Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快速创建Angular组件并定义传参、绑
- 下一篇: Angular的ChangeDetect