Introduction to Modules in Angular
The Angular Framework is inherently modular, thanks to NgModule, which simplifies code organization. NgModule plays a pivotal role in Angular apps, enabling the creation of distinct modules that can be loaded as needed via lazy loading. Every Angular app begins with AppModule as the root module in app.module.ts, bootstrapping the application. Additional feature modules are common, with the root NgModule encompassing all child NgModules, regardless of hierarchy depth.
A Basic Use of Modules
- An NgModule is a class marked by the @NgModule decorator
- NgModule is a collection of directives, components, pipes, services, other dependency modules, providers, etc.
- It creates a logical boundary for dependencies resolution.
- It helps to organize related things together.
- It can control what can be exposed from @NgModule.
NgModule Metadata
You can pass configuration in metadata@NgModule decorator
option | Description |
---|---|
declarations | Things used on HTML belonging to this NgModule like components, directives, and pipes |
exports | The subset of declarations that should be reusable in the component templates of other NgModules |
imports | Other modules whose exported (components, directives, pipes) classes and services are needed in this NgModule. |
providers | Creators of services that this NgModule contributes to the global collection of services |
bootstrap | The main application view (entry point), called a root component, hosts all other application views. Only the root NgModule should set the bootstrap property |
Declarations Array
- declarations array consist of classes that are used on HTML from the NgModule
- Component
- Directive
- Pipe
- Without declaring these classes inside the declarations array, they can not be used on HTML.
Providers Array
- It contains
- Configurable dependencies
- Providers / Services
Imports Array
- Imports other @angular NgModule where the current module is dependent on
- From imported NgModule we can use exported classes on current module component templates
- Providers (services) will also be available for injection and use.
- To use 3rd party library features, include respective NgModule in the desired module, wherever you wanted to use library features.
Exports Array
- export NgModules, components, pipes, and directives, that can be used by importer NgModule.
- To export components/pipes/directives, they should also be a part of the declarations array.
- If we don't export the aforementioned classes, you would see an error in the console for eg. 'my-component' is not a known element
Bootstrap
- Mention which component should be the root of an application.
- Ideally, there should be a single root component per application.
- But there could be cases, that you may add multiple root components in the bootstrap option.
NgModules and Components
NgModules | Components |
---|---|
It collates different building blocks of an application together | Component consists of the template and its associated class |
It has providers array to resolve dependencies | Component instance has change detector for resolving dependencies |
It forms injector tree for lazily loaded module | Components create view DOM tree for nested components |
NgModule providers are lookup after components providers | Change detector resolve dependency on component level, then NgModule level |
NgModules and JavaScript Modules
NgModules | Javascript Modules |
---|---|
Angular specific construct | JS modules are part of the browser itself |
It combines different pieces of Angular Framework under a single block | It can import or export function/variables/classes |
It helps to divide an application into small blocks | ES module help to modularize code |
Encapsulates code to hide implementation details | helps to create a boundaries between different parts of an application |
Accepts metadata configuration | It does not accept any metadata configuration object |
helps to keep the Separation of concerns | Avoid leaking code to the global namespace |
Angular Module Example
Below is an example of a Simple NgModule
Create the Application
You can run below command in command line / terminal. This helps to create a brand new angular application.
- ng new - helps to create a new angular project
- employee-management - project and folder name
- --prefix=em - is selector prefix used when new components/directives are generated.
Routing Module
- When creating an app, it would ask to enable routing, just say "YES" there.
- It automatically adds AppRoutingModule
- It would have empty routes registered with RouterModule's forRoot method.
- Add fallback route to routes array using wildcard (**) check
Root Module
- AppRoutingModule is already imported in AppModule imports arrray
Creating a Module
Again, you can use CLI for generating NgModule.
Generate NgModule Using CLI
It generates HomeModule inside home folder
home.module.ts
Components
Create Home Component
- ng g c home - Create a HomeComponent
- --module=home.module - Declare HomeComponent under declartions of HomeModule
Folder Structure
You can additionally add routing of HomeModule, register home path against HomeComponent with the help of RouterModule's forChild method.
home.module.ts
Using HomeModule in AppModule
- Import HomeModule inside a Root Module i.e. AppModule
- This way we extended the RootModule with the feature NgModule.
Create NgModule and Component along with Routing Using CLI
We've already said this multiple times, Angular CLI is helping developers by automating most of the stuff. There should be something to simplify these many file creation. Yo! that's possible, you would just need to fire the below command to generate the scaffold files.
Let's try to understand the above command in parts
- ng generate module home - Generate home.module.ts
- --route home - Create a HomeComponent
- --route home - Create route configuration for the HomeComponent, and mentions it in imports of a home.module.ts
- --module app.module - Include the HomeModule inside AppModule.
Changes in app.component.html
Add placeholder for router, to keep watch on URL and render a matched view inside it.
Angular Libraries
Module | Description |
---|---|
CommonModule / BrowserModule | Most of the common components, directives, services, and pipes |
RouterModule | Routing related Component, directives and services are imported from here |
HttpClientModule | API for making HTTP calls |
FormsModule | For template-driven form |
ReactiveFormsModule | For model driven form |
ElementModule | use methods to create web components from it |
i18nModule | Use for i18n or localization |
Bootstrapping an Application
Application has to be bootstrap by calling bootstrapModule method, which accepts the root module in angular (AppModule) from main.ts.
Conclusion
- What is module in angular?
- How to create a NgModule?
- How feature module created and imported?
- Difference between NgModule vs EsModule.
- Various metadata options exist for the NgModule metadata decorator.