How to determine if a module should be imported into CoreModule or SharedModule

Viewed 321

In an angular4 application, given the followiing modules:

  • ReactiveFormsModule,
  • FormsModule,
  • HttpModule,
  • TranslateModule, (the translate module)
  • AgGridModule.withComponents( [] ), (a table framework)
  • DatepickerModule.forRoot(), (and in general modules of ngx-bootstrap)

Where is the correct place to import them: CoreModule or SharedModule ?

Thanks in advance

3 Answers

It depends on whether:

  • these modules define declarable types: components, directives or pipes.
  • shared module are used in lazy loading

If they define declarables and you want to reuse them it's better to import the module into Shared module. If they don't, put them into Core module.

If shared modules are used in lazy loading, then you don't want to create another instance of the service and should import them into Core module. Usually these modules have forRoot or forChild methods defined, like for DatepickerModule.forRoot().

So, for the modules in question:

  • ReactiveFormsModule - shared
  • FormsModule - shared
  • HttpModule - core
  • TranslateModule - core (has services)
  • AgGridModule.withComponents( [] ) - shared
  • DatepickerModule.forRoot() - core

For more information read Avoiding common confusions with modules in Angular

best way to import modules. I hope you using page lazy loading.

These modules should imported in Root/Core module

ReactiveFormsModule, FormsModule, HttpModule,

This is optional you can import in Root/Core incase you required in all pages other wise import individually in page modules.

TranslateModule()

These modules can import individual modules of dependent pages.

AgGridModule.withComponents( [] ), (a table framework) DatepickerModule.forRoot(), (and in general modules of ngx-bootstrap)

and each root components and the root definitions should be placed in CoreModule or in AppModule ?

Related