Wednesday, November 14, 2018

Share a Component

We cannot share a component to different modules by just importing that component inside all the modules, because Angular 2 doesn’t allow us to import single component to different modules, if you try to do this then Angular will throw an error:
    Type X(component) is part of the declarations of 2 modules


So, for solving this problem we create a Shared Module instead of sharing a component, now we share this module in all other modules for this we use import statement and import the shared module in all other modules after this the component will gets automatically shared to all the modules.

Below is the example of how to do it:
SharedModule

1
2
3
4
5
6
7
8
9
10
11
12
13
@NgModule({
    imports: [
        SomeModule
     ],
    declarations: [
         SharedComponent
    ],
    exports: [
        SharedComponent
    ]
})
  
export class SharedModule {}
app.module.ts

1
2
3
4
5
6
7
8
import { SharedModule } from './shared/shared.module;
  
@NgModule({
    imports: [ SharedModule],
     ...
})


As you can see above we create a SharedModule and then import it in the AppModule, now the SharedComponent is shared and available in all the modules via AppModule, If you want to use the SharedModule  in some specific module then don’t import it in the AppModule instead import it in those modules.

Note: If I don’t provide the SharedComponent inside the exports array of the SharedModule then that component will not be available outside that module, so don’t forget to export the component. Similarly you can share the Directives, Pipes and Modules, just provide them inside the exports array of shared module.

Source : https://www.oodlestechnologies.com/blogs/How-to-share-component-to-multiple-modules-in-Angular2

No comments:

Followers

Link