许多使用相同组件的模块会导致错误 - Angular 2

时间:2016-10-08 00:09:07

标签: angular ng-modules

我有一个名为GoComponent的共享组件,我想在2个模块中使用:FindPageModule和AddPageModule。

当我在" FindPageModule"的声明中添加它时在我的" AddPageModule"我收到一个错误:

  

find:21错误:(SystemJS)类型GoComponent是声明的一部分   2个模块:FindPageModule和AddPageModule!请考虑搬家   GoComponent到一个导入FindPageModule和的更高模块   AddPageModule。您还可以创建一个导出和导出的新NgModule   包括GoComponent然后在FindPageModule和中导入NgModule   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>
"): FindFormComponent@101: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>
"): FindFormComponent@101:4

如何让在FindPageModule中声明的FindFormComponent等组件使用GoComponent,并让AddPageModule声明的组件使用GoComponent?

2 个答案:

答案 0 :(得分:36)

是的,组件只能在一个模块中声明,并且它们的访问权限也不会以任何方式继承,这意味着在主应用程序模块中声明它不会让您在任何其他模块中访问它。

如果您有其他模块使用的组件,通常他们可以将其放在共享模块中

在共享模块中包含组件:

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

如何在其他地方使用共享模块:

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

另见

答案 1 :(得分:1)

如果要在多个模块中使用GoComponent,则应创建一个“共享”模块,并将GoComponent添加到共享模块的导出中。然后将共享模块导入到要使用此组件的其他模块中。

here

了解更多信息

希望这有帮助!