如何在多个 module.ts 文件中注册组件

How to register component in multiple module.ts files

我们可以在多个 module.ts 文件中注册相同的组件吗?。如果可以,有什么方法可以实现?

Can we register (the) same component in multiple module.ts files?

没有。为了在整个应用程序中重复使用单个组件,您必须创建一个共享模块来声明和导出该组件。然后,在任何需要组件的地方导入这个共享模块。

共享模块:

@NgModule({
  declarations: [
    YourComponent,
  ],
  imports: [
    ...
  ],
  exports: [
    YourComponent,
  ],
  providers: [
    ...
  ],
})
export class SharedModule {
}

FeatureOneModule:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    SharedModule,
  ],
  exports: [
    ...
  ],
  providers: [
    ...
  ],
})
export class FeatureOneModule {
}

FeatureTwoModule:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    SharedModule,
  ],
  exports: [
    ...
  ],
  providers: [
    ...
  ],
})
export class FeatureTwoModule {
}

然后您将能够在 FeatureOneFeatureTwo-Module 中相应地使用 YourComponent。 Angular 提供了很棒的 guide here.