Reputation: 489
I would like to use some components in different modules. Currently my modular system is structured as follows
Now one wants to create a component, e.g. InputControlComponent, which I can use in components of AdministrationModule as well as in the ProfileModule.
My first idea was this
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { InputControlComponent } from './form/inputControl.component';
@NgModule({
declarations: [
InputControlComponent
],
providers: [
],
imports: [
CommonModule,
],
exports: [
InputControlComponent
]
})
export class SharedModule {
constructor(
) {
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
[...]
import { SharedModule } from './shared/shared.module';
@NgModule({
declarations: [
AppComponent,
[...]
],
providers: [
[...]
],
imports: [
CommonModule,
[...]
AdministrationModule,
SharedModule,
RouterModule.forRoot([
{ path: 'home', component: HomeComponent },
{ path: '**', component: PageNotFoundComponent },
]),
]
})
export class AppModuleShared {
constructor(
) {
}
}
But my InputControlComponent cannot be found.
Upvotes: 1
Views: 1822
Reputation: 708
I would divide it a bit differently.
At the level of your app.module you can create "modules" folder where you will put your main components like admin module or profile module - each in separate file.
If you have blocks of code which are shown almost everywhere like header or footer you can create blocks folder ( same level as app.module ) and put it there.
About MyButton I think it's good idea to create another file called Shared and put it there so you can easily import it where you need it.
So basically it would look like
You can easily import shared.module in all modules where you would like to make use of your button component.
Upvotes: 1
Reputation: 360
It seems that you are going in right direction, find the link in the end of this post and verify your logic. The whole logic should be :- 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.
You can find detailed description here:-
https://www.oodlestechnologies.com/blogs/How-to-share-component-to-multiple-modules-in-Angular2
Upvotes: 0