Joan Miquel
Joan Miquel

Reputation: 286

Shareable angular component

Given this app structure:

So I need to create a "shared component" that I know it will just be shared between Modules 1 and 2 and can't be used anywhere else. Should I create it as a normal shared component?

Thanks in advance.

Upvotes: 0

Views: 153

Answers (2)

Alf Moh
Alf Moh

Reputation: 7427

DeborahK's answer is right but per your comment, I believe you didn't really get it so here is further elaboration.

To share a component between Module 1 and Module 2, you will have to create a Shared Module. In the exports array of the shared module, you'll export the component you would want to share. Now, in the imports array of the Module 1 and Module 2, you will import the Shared Module. This way, the exported component will be available for both Module 1 and Module 2.

Your app structure will look like something like this.

  • Module 1
  • Module 2
  • Module 3
  • Module 4
  • Shared (folder)
    • Shared Module
    • Shared component 1
    • Shared component 2

In the shared.module.ts, you'd have something like this.

exports: [SharedComponent]

In the module1.ts and module2.ts, you also have something like this.

imports:[SharedModule]

Upvotes: 0

DeborahK
DeborahK

Reputation: 60518

If you don't add the shared module to the imports array of the other modules, those components won't be shared with the other modules.

For example:

My ProductModule includes SharedModule in its imports:

@NgModule({
  imports: [
    SharedModule, 
    RouterModule.forChild([...])
  ],
  declarations: [
    ProductListComponent,
    ProductDetailComponent,
    ProductEditComponent,
  ],
  providers: [
    ProductService
  ]
})
export class ProductModule { }

So only the Product Module's components can access the shared module's components.

Any module that should not use the Shared Module, don't add it to it's imports array.

Upvotes: 1

Related Questions