Angular modules help us to organize the application into cohesive blocks of related functionality. Angular modules are much similar to packages in java and namespaces in c#
Roles of an Angular Module
- Imports Other Angular Modules
- Identify components, pipes, and directives
- Export Its features
- Can be eagerly or lazily loaded
- Root Module
- CORE Module
- Shared Module
- Feature/Widget Module
Every Angular application requires at least one module. Root Module is responsible for loading the root component and other parts of our app and any Angular-specific dependencies.
By convention, the root module is called as AppModule and get created under the ‘./src/app’ folder.
Core modules should contain only the services, components and others that can be imported only once per application. Core Module must be only imported in AppModule and must prevent from loading from other modules.
This is especially important if you intend to lazy-load your feature modules. Since lazy-loaded modules are loaded on demand (when you access the route using the lazy-loaded feature), you could end up creating new instances of singleton services if you don’t put them in CoreModule.
Shared Module contains the code that can be used across the project. Shared Modules can be imported into the feature modules on a need basis. Shared Module cannot be imported into AppModule or CORE Module strictly.
These components don’t import and inject services from the core or other features in their constructors.
A featured module consists of a cohesive set of functionality focused on a specific application need such as a user workflow, routing, or forms. The main aim for feature modules is delimiting the functionality that focuses on particular internal business inside a dedicated module, in order to achieve modularity.
The featured module helps us to split the application into multiple modules which interns make the Root module thin so that the initial page loads quickly
Declarations: It is for things that you use your HTML templates/views. It includes components, directives, and pipes
Providers: for services
Imports: for importing external modules that the current module depends on
Exports: exports used to export the components, pipes, directives to use them in other modules within the application.
The confusion starts with components and services not having the same scope/visibility
- declarations / components are in local scope (private visibility),
- providers/services are (generally) in the 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.
Originally published at http://www.techmonks.org on December 25, 2019.