I am going through the example of Angular2 Material and I see that all Material modules are imported in the root module using the forRoot()
method. So in my app I do the same.
Now I need to use some Material components within other Shared modules, which means that I need to import the related Material packages in my Shared module. I am not clear whether I need to use the forRoot()
method also while importing them in the Shared module.
Thanks in advance for any help
forRoot
is only used for the main app module. It is a convention used so that only the app module gets application/singleton providers. This is to avoid providers that are supposed to be singletons, being created more than once for the application. For exampleHere we should only call
forRoot
while importing into the app module, so that it can create theAuthProvider
only once as a singleton. All other modules that need theSharedModule
should simply importShareModule
so that it can use theSharedDirective
.So calling
forRoot
in the app module gets you everything provided by that module (and conventionally the providers that come with callingforRoot
) into the app module. So all the components declared in your app module have access to to everything from that module.But everything in the
declarations
(this include components, directives, and pipes) isn't inherited by any sub-modules. So we still need to import the module into any other module we need it in.Your question seems to be specifically about your
ShareModule
. For this module, you should not useforRoot
, for reasons I mentioned above. You should justexports
the MD module(s). You only useimports
if some component declared in thatSharedModule
actually requires any MD modules. For example, if you have a component that uses the MD button, and that component is a shared component that you declare in theSharedModule
. In this case you shouldimports
andexports
. But if there are no such components, you only need toexports
. This provides the MD module(s) to whatever module you import theSharedModule
into.