![](/img/trans.png)
[英]Angular 7.2 - “component is part of the declarations of 2 modules” but it is not
[英]Component is part of the declarations of 2 modules in Angular
我創建了一個名為commonmod.component.ts的組件,我將其包含在其他兩個模塊(abc 和 def)中。
abc.module.ts
import { commonmod } from '../commonmod/commonmod.component';
@NgModule({
declarations: [
commonmod
]
})
def.module.ts
import { commonmod } from '../commonmod/commonmod.component';
@NgModule({
declarations: [
commonmod
]
})
當我將 abc 模塊中的一個頁面重定向到 def 模塊中的另一個頁面時,它拋出以下錯誤。
錯誤錯誤:未捕獲(承諾):錯誤:類型 commonmod 是 2 個模塊聲明的一部分:abcand def。 請考慮將 commonmod 移動到導入 abc 和 def 的更高模塊。 您還可以創建一個新的 NgModule,它導出並包含 commonmod,然后在 abcand def 中導入該 NgModule:錯誤:類型 commonmod 是 2 個模塊聲明的一部分。 abc 和 def。 請考慮將 commonmod 移動到導入 abcand def 的更高模塊。 您還可以創建一個新的 NgModule,它導出並包含 commonmod,然后在 abc 和 def 中導入該 NgModule。
一個組件只能在一個模塊中聲明。 如果你試圖在多個模塊中聲明它,你會得到這個錯誤
錯誤:類型...是 2 個(或更多)模塊聲明的一部分:
這個問題的解決方案非常簡單。 如果您需要在多個模塊中使用一個組件,則將其添加到聲明它的模塊的導出數組中。
假設我們有一個名為GreetingsComponent的組件,它在模塊TestModule中聲明,我想在AppModule 中聲明的 AppComponent中使用它。 我將像這樣簡單地將它添加到TestModule的導出數組中
import {NgModule} from '@angular/core';
import {GreetingComponent} from './greeting.component';
@NgModule({
declarations:[GreetingComponent],
exports:[GreetingComponent]
})
export class TestModule
{
}
現在,由於AppModule已經導入了TestModule ,並且通過這種方式所有構造是否在TestModule的導出數組中的組件、指令、管道等應自動對 AppModule 可用。
AppModule.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import {TestModule} from './test.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule, TestModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
現在您可以簡單地在 AppComponent 中使用 GreetingsComponent
<greetings></greetings>
這里有一個工作的StackBlitz 。
干杯。
您不能在多個模塊中聲明一個組件。 如果兩個模塊都需要它,您需要在第三個模塊中聲明/導出您的組件,並在 abc 和 def 中導入該組件。
@NgModule({
imports: [ MainModule ]
})
export class AbcModule { }
@NgModule({
imports: [ MainModule ]
})
export class DefModule { }
@NgModule({
declarations: [ CommonMod ],
exports: [ CommonMod ]
})
export class MainModule { }
如果您在 Angular 9+ 中使用 HMR(熱模塊替換),也可能會發生這種情況。 Angular 團隊正在努力解決這個問題。
有關更多詳細信息和更新,請參閱此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.