4

I am developing an app that is starting to have many components. I'd like to break the components into separate modules, to avoid the app module listing many many components, and the code becoming disorganized.

I have a component, ImageUploadComponent, that I plan to use across multiple other components.

I created a module, ProductsModule, that imports and declares all the components that are specifically related to Products.

import { ProductsComponent }       from './products.component';
import { ProductDetailComponent }  from './product-detail.component';

...

@NgModule({
  declarations: [
      ProductsComponent,
      ProductDetailComponent
  ],
  ...
})
export class ProductsModule { }

In app.module, I import both ProductsModule and ImageUploadComponent:

import { ProductsModule } from './products/products.module';
import { ImageUploadComponent } from './shared/image_upload.component';
...
@NgModule({
  declarations: [
    ...
    ImageUploadComponent,
  ],
  imports: [
    ...
    ProductsModule,
  ],
  ...
})
export class AppModule { ... }

However, the ProductsModule does not know about the ImageUploadComponent, and thus, trying to use the ImageUploadComponent within the ProductsComponent results in an error.

How do I break my code into separate modules in Angular2 in such a way that a shared component can be used across all the modules?

My version of Angular is 2.1.1.

1 Answer 1

6

You have to create a module for ImageUploadComponent and import it in AppModule and ProductsModule.

For you to be able to use a component inside another module, you have to export the component, something like:

import { ImageUploadComponent } from './shared/image_upload.component';
...
@NgModule({
  declarations: [
    ImageUploadComponent,
  ],
  exports: [
    ...
    ImageUploadComponent, // Here you dispose the component to other modules
  ],
  ...
})
export class ImageUploadModule { ... }

Why not load it only in ProductsModule? Because if you do not load it in appModule you will end up with an instance of ImageUploadComponent in each module that imports it.

Angular share instances between parent and children modules not between brothers..

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.