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

Ben*_*ins 18 ng-modules angular

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

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

find:21错误:(SystemJS)类型GoComponent是2个模块的声明的一部分:FindPageModule和AddPageModule!请考虑将GoComponent移动到导入FindPageModule和AddPageModule的更高模块.您还可以创建一个新的NgModule,它导出并包含GoComponent,然后在FindPageModule和AddPageModule中导入该NgModule.

所以我把它们从它们中取出并将它添加到AppModule声明中,它确实导入了FindPageModule和AddPageModule,并且在FindPageModule声明中使用"GoComponent"的组件中出现了一个名为"FindFormComponent"的组件中的错误:

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
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*tha 39

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

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

在共享模块中包含组件:

@NgModule({
  declarations: [ SharedComponent ],
  exports: [ SharedComponent ]
})
class SharedModule {}
Run Code Online (Sandbox Code Playgroud)

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

@NgModule({
  imports: [ SharedModule ]
})
class ModuleWithComponentThatUsesSharedComponent {}
Run Code Online (Sandbox Code Playgroud)

也可以看看

  • 似乎有不止一些人不熟悉这个想法:https://github.com/angular/angular/issues/10646 (2认同)
  • 出口是我所缺少的 (2认同)