angularangular2-material

Importing modules with forRoot()


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


Solution

  • 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 example

    import { ModuleWithProviders } '@angular/core';
    
    @NgModule({
      declarations: [ SomeDirective ],
      exports: [ SomeDirective ]
    })
    export class SharedModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: SharedModule,
          providers: [ AuthProvider ]
        }
      }
    }
    

    Here we should only call forRoot while importing into the app module, so that it can create the AuthProvider only once as a singleton. All other modules that need the SharedModule should simply import ShareModule so that it can use the SharedDirective.

    So calling forRoot in the app module gets you everything provided by that module (and conventionally the providers that come with calling forRoot) 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 use forRoot, for reasons I mentioned above. You should just exports the MD module(s). You only use imports if some component declared in that SharedModule 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 the SharedModule. In this case you should imports and exports. But if there are no such components, you only need to exports. This provides the MD module(s) to whatever module you import the SharedModule into.