Understanding Angular modules (NgModule) and their scopes
NgModule is the first basic structure you meet when coding an app with Angular, but it’s also the most subtle and complex, because of different scopes. Angular documentation has done a whole FAQ about NgModules, but it’s still quite a mess to teach this during courses, students are often confused, so I decided to sum it up in this post for everyone.
Why NgModule ?
The purpose of a NgModule is to declare each thing you create in Angular. There is two kind of main structures :
- “declarations” is for things you’ll use in your templates : mainly components (~ views : the classes displaying data), but also directives and pipes ;
- “providers” is for services (~ models : the classes getting and handling data).
Why do we need to register everything ? NgModule was a structure introduced lately in the RC phase of Angular 2. First, it seemed unnecessary complexity, as it feels redundant with ES6 imports. But now we’re used to it, you can rejoice : it allows Ahead of Time (AoT) compilation, which is amazing for performance. And it may seems heavy at first, but it actually saves you many lines of imports : in beta versions of Angular 2, you needed to import your components and directives every time you used them (good luck if you use UI modules like Material).
NgModule and scopes / visibility
The confusion starts with declarations and providers not having the same scope / visibility :
- declarations / components are in local scope (private visibility) ;
- providers / services are in global scope (public visibility).
It means the components you declared are only usable in the current module. If you need to use them outside, in other modules, you’ll have to export them :
On the contrary, services you provided will be available / injectable anywhere in your app, in all modules.
When to import a NgModule ?
The difference of scope between components and services is an important point to know, but for now it’s still OK. Things get messy because, of course, as in any framework and app, you won’t just have one module, but many of them. Angular itself is subdivided in different modules (core, common, http and so on).
So another main thing you do in an Angular module is to import other NgModules you need :
Problem is : you need to know why you import these other modules.
- Is it to use components (or other template-related things, like directives and pipes) ?
- or is is to use services ?
Why ? Because given the difference of scope between components and services :
- if the module is imported for components, you’ll need to import it in each module needing them ;
- if the module is imported for services, you’ll need to import it only once, in the first app module.
If you fail to understand this, you’ll have errors on components not being available, because you forgot to import their module again.
Or if you import a module for services more than once, you’ll create several instances of the same service in your app, which can lead to errors, but more importantly is bad for performance.
When to import main Angular modules ?
A good knowledge of Angular modules is then required, to know how many times you need to import them. Here is an helpful summary.
Modules to import each time you need them
- CommonModule (all the basics of Angular templating : bindings, *ngIf, *ngFor…), except in the first app module, because it’s already part of the BrowserModule
- FormsModule / ReactiveFormsModule
- MaterialModule and UI modules (like PrimeNg)
- any other module giving you components, directives or pipes
Modules to import only once
- HttpClientModule / HttpModule
- any other module providing you services only.
The SharedModule good practice
That’s why with Angular CLI, CommonModule is automatically imported when you create a new module.
If you use other components-related modules like animations, flex layout or Material, it will be tiring to have to import their modules every time. So a good practice is to create a SharedModule to factorize.
But be careful how you manage this. It won’t work if you just import the modules :
Why ? Still a scope problem : the components will be available in the SharedModule itself. But it’s not where you’ll use them, it’s in other modules which include this SharedModule. So you need to export them :
If your SharedModule includes other shared things (like the app menu), stay on the previous code. But if your SharedModule is just here to factorize and doesn’t include anything else, you can simplify by skipping the imports property :
It can get messier : how to manage modules with components and services at the same time ?
You know one of them : the RouterModule. It gives you a component (<router-outlet>) and a directive (routerLink), but also services (ActivatedRoute to get URL params, Router to navigate…).
Fortunately, the mess is managed by the module itself. Routing files are automatically generated by Angular CLI, but you may have noticed there is a subtle difference between the routing of your first app module and the routing of submodules.
For the AppModule, it does :
For submodules, it does :
Why ? Because the first time in app module, forRoot() will give the router components and provide the router services. But the next times in submodules, forChild will only give the router components (and not providing again the services, which would be bad).
Last complication : if you lazy-load a module, which is now easy with Angular CLI.
As it will be a different bundle and module, loaded only on demand by default, it’s not included in the global scope your app.
For components, it doesn’t change anything : you need to import again the CommonModule or your SharedModule, like in any submodule.
For services, there is a difference :
- you’ll still have access to services already provided in the app (like Http and your own services) ;
- but the services provided in your lazy-loaded module will only be available in this lazy-loaded module, not everywhere in your app.
Conclusion : why ?
Now you know everything about Angular modules, you may ask : why this mess ? Well, it may be difficult for beginners, but there is a good reason :
- services are mostly just ES6 classes : they are imported/exported, so in their namespaces, so no risk of collision !
- components create… components, ie. new HTML tags : if they were global, loading two librairies creating components with the same name would create conflicts.
Hope I demystified NgModule. :)