如何将组件包含在两个独立的模块中?

How to include a component in two separate modules?

我有两个模块:ItemsListModuleSearchModule

ItemsListModule 换行 ItemsListComponentSearchModule 换行 SearchComponent.

ItemsList在页面上用来显示项目列表,我也想在Search中使用它来显示结果列表。换句话说:在 SearchComponent 内,我也想使用 ItemsListComponent

// SearchModule
@NgModule({
  declarations: [SearchComponent],
  imports: [SearchRoutingModule],
})

// ItemsListModule
@NgModule({
  declarations: [ItemsListComponent],
  imports: [],
})

// AppModule
@NgModule({
  declarations: [AppComponent],
  imports: [ItemsListModule, SearchModule],
})

当我在 SearchComponent 的模板中使用 <my-items-list> 时,我收到一个错误,指出该组件是未知的,请确认它是 SearchModule 的一部分。如果我将它添加到 SearchModule 的导入中,我会收到相同的错误消息。

为什么?如何重复使用 ItemsList 来显示我的搜索结果? (Angular 8.3)

ItemListModule 导出您的 ItemListComponent 并在 SearchModule

中导入此模块

搜索模块

    @NgModule({
      declarations: [SearchComponent],
      imports: [SearchRoutingModule, ItemListModule],
    })

ItemsListModule

    @NgModule({
      declarations: [ItemListComponent],
      exports: [ItemListComponent]
    })

ItemsListModule

        @NgModule({
          declarations: [ItemsListComponent], // declare Item list component here
          imports: [],
          exports: [ItemListComponent]
        })

搜索模块

        @NgModule({
          declarations: [SearchComponent],
          imports: [SearchRoutingModule,
                    ItemsListModule], //  import ItemListModule Here

        })  

and try to use <my-items-list> in search.component.html, it will work.

您需要在 SearchModule 中的 entrycomponents 中添加 ItemsListComponent 像这样

@NgModule({
declarations: [ 
   ItemsListComponent
],
entryComponents: [
    ItemsListComponent
  ]
})