如何在Angular 2中的模块之间共享组件?

use*_*696 13 components web-component angular

我对如何在Angular 2中的模块之间共享组件存在疑问.重点是:我在应用程序中有两个模块,即"客户模块"和"供应商模块".

这些模块在其组件中都使用了AddressComponent和EmailComponent.他们也都使用接口地址和电子邮件.

现在,我目前有很多重复,因为我已经在这两个模块上复制并粘贴了这些组件和接口.这显然是完全错误的.

我需要一种方法来导入要在两个模块上使用的组件.但我不知道该怎么做.

我应该为这个共享的东西创建另一个模块并将其导入两者吗?在Angular 2中共享模块之间的组件的正确方法是什么?

Pan*_*kar 18

创建一个NgModule将拥有所有常用Component/ Service/ 的共享Pipe.通过这样做,您将避免代码重复.它将使代码模块化,可插拔和可测试.

要在其他模块中使用AddressComponent&EmailComponent,您需要export从共享模块中使用它们:

@NgModule({
   imports: [CommonModule],
   declarations: [AddressComponent, EmailComponent],
   providers: [MySharedService],
   exports: [AddressComponent, EmailComponent],
})
export class SharedModule() { }
Run Code Online (Sandbox Code Playgroud)

消费时SharedModule,你所要做的就是进口SharedModule

@NgModule({
   imports: [CommonModule, SharedModule, ... ],
   providers: [..]
})
export class CustomersModule() { }
Run Code Online (Sandbox Code Playgroud)