POV
POV

Reputation: 12015

Why I should include CommonModule in child modules?

Why I should include CommonModule in child modules if this module already was included in main module AppModule?

AppModule(Root) -> includes -> CommonModule
CustomModule -> incudes -> CommonModule
AppModule -> incudes -> CustomModule>

I think CommonModule is redundant in CustomModule, because it is globally declarated in CommonModule? isn't it ?

Upvotes: 1

Views: 873

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39442

That's because if you want to use any of the exported features(Component, Directive, Pipe) of the CommonModule in your CustomModule, you can't do that without adding the CommonModule to the imports array of the CustomModule.

If you imported the CommonModule in your AppModule, you'll only be able to use the exported members of CommonModule in the registered(added to the declarations) Components, Directives, Pipes etc of the AppModule. If you export the CommonModule from the AppModule, since AppModule is your Root Module and you will not add it to the imports array of any other module, you won't be able to use the exported members of the CommonModule anywhere else, unless imported there as well.

You can use services from CommonModule(although it's not recommended) in the CustomModule(if providedIn: 'root') since they are registered on the Root Injector. But apart from that, nothing else would be usable unless its imported.

Why providing services from CommonModule(or SharedModule whatever you want to call it) is not recommended?

From Angular Style Guide:

Consider not providing services in shared modules. Services are usually singletons that are provided once for the entire application or in a particular feature module. There are exceptions, however. For example, in the sample code that follows, notice that the SharedModule provides FilterTextService. This is acceptable here because the service is stateless;that is, the consumers of the service aren't impacted by new instances.

Upvotes: 4

Related Questions