【问题标题】:Many Modules using the same component causes error - Angular 2使用相同组件的许多模块会导致错误 - Angular 2
【发布时间】:2017-02-17 01:12:09
【问题描述】:

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

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

find:21 错误:(SystemJS)类型 GoComponent 是声明的一部分 2 个模块:FindPageModule 和 AddPageModule!请考虑搬家 GoComponent 到导入 FindPageModule 的更高模块和 添加页面模块。你也可以创建一个新的 NgModule 来导出和 包括 GoComponent 然后在 FindPageModule 中导入该 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

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

【问题讨论】:

    标签: angular ng-modules


    【解决方案1】:

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

    如果你有一个组件被其他模块使用,通常他们的方法是将它放在一个共享模块中

    在共享模块中包含组件:

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

    如何在别处使用共享模块:

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

    另见

    【讨论】:

    【解决方案2】:

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

    通过here了解更多信息

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 2021-04-26
      • 2019-11-03
      • 2010-11-16
      • 1970-01-01
      • 2020-04-30
      • 2016-08-13
      相关资源
      最近更新 更多