Search code examples
angularangular2-materialangular2-modules

Angular 2 use a module without importing it


This may sounds dumb, but I would like to know if there's a way of importing a module once, and making it available for all child modules.

For instance, I want to use MaterialModule in all my modules. Currently, I have to import it in every module, declare it, and then I can use it.

I tried putting it only in the app module, exporting it, but it doesn't seem to be effective.

So my question is : Is it possible to declare a module in the app module, so that we can use it without declaring it in the child modules ?


Solution

  • It depends what the module contains.

    Take the HttpModule from Angular for instance. You can just import it once in the root module and then inject the Http service anywhere in your application. That's because it contains services (among other things) and services declared in @NgModule.providers are injectable globally.

    However, if your module contains components, directives, etc. (which I suspect MaterialModule does), then you do need to import it explicitly in any module where these components, directives, etc. are used.

    What you could do to mitigate the hassle is create a SharedModule that re-exports all functionality that is reused throughout your app. That way, you only have to import that one module in the other modules requiring the shared functionality. That means you still have at least one import per module, but that's already the case anyway, since you most probably need something like CommonModule in all of your modules. (I believe this SharedModule technique is what the official doc recommends in the Module section).