2016-10-08 38 views
9

我有一個名爲GoComponent的共享組件,我想在兩個模塊中使用:FindPageModule和AddPageModule。許多使用相同組件的模塊導致錯誤 - Angular 2

當我在「FindPageModule」的聲明,並在我的「AddPageModule」添加它,我得到一個錯誤:

find:21 Error: (SystemJS) Type GoComponent is part of the declarations of 2 modules: FindPageModule and AddPageModule! Please consider moving GoComponent to a higher module that imports FindPageModule and AddPageModule. You can also create a new NgModule that exports and includes GoComponent then import that NgModule in FindPageModule and AddPageModule.

所以我把它拿出他們兩人,並添加它的AppModule聲明,它不進口FindPageModule和AddPageModule,我得到一個錯誤在一個名爲「FindFormComponent」組分,它是在FindPageModule的聲明,並使用「GoComponent」:

zone.js:355 Unhandled Promise rejection: Template parse errors: 
'go' is not a known element: 
1. If 'go' is an Angular component, then verify that it is part of this module. 
2. If 'go' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. (" style="height:64px;"> 
      <div style="position: relative; display: inline-block; width: 100%;"> 
       [ERROR ->]<go></go> 
      </div> 
     </div> 
"): [email protected]:4 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors: 
'go' is not a known element: 
1. If 'go' is an Angular component, then verify that it is part of this module. 
2. If 'go' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. (" style="height:64px;"> 
      <div style="position: relative; display: inline-block; width: 100%;"> 
       [ERROR ->]<go></go> 
      </div> 
     </div> 
"): [email protected]:4 

如何讓組件如FindFormComponent了在FindPageModule聲明使用GoComponent a還讓由AddPageModule聲明的組件使用GoComponent?

回答

19

是的,組件只能在一個模塊中聲明,它們的訪問也不以任何方式繼承,也就是說在主應用程序模塊中聲明它不會讓你在任何其他模塊中訪問它。

如果你所使用的其他模塊組件,通常他們的路要走是把它共享的模塊中

包括共用模塊組成:

@NgModule({ 
    declarations: [ SharedComponent ], 
    exports: [ SharedComponent ] 
}) 
class SharedModule {} 

如何使用別處所述共享模塊:

@NgModule({ 
    imports: [ SharedModule ] 
}) 
class ModuleWithComponentThatUsesSharedComponent {} 

參見

+2

似乎還有比這並不是真正的臀部這個想法有幾個人更多:https://github.com/angular/angular/issues/10646 – Brandon

1

如果您想跨多個模塊使用GoComponent,應該創建一個「共享」模塊並將GoComponent添加到共享模塊的導出。然後,將共享模塊導入您想要使用此組件的其他模塊。

here

希望這有助於瞭解更多信息!

相關問題