The module is the main Building Block of Angular which is the group of components, directives, pipes, and services that are the parts of the Angular application.
We use
ngModule
metadata object for defining the module that instructs Angular how to compile and run the application.
1 2 3 4 5 6 7 8 9 | import { NgModule } from '@angular/core'; @NgModule({ declarations: [here will be your Components], imports: [Import your module], providers: [Here will be your services], bootstrap: [Here will be your default component that will load] }) export class AppModule { } |
What is NgModule in Angular
NgModule is a class that is created by the @NgModule decorator. It takes a metadata object that’s described how to compile the component’s template and create an injector at runtime. It defines the module’s own components, directives, pipes, and services and makes some of them public, allowing external components to use them via the exports property.
NgModule uses below metadata properties:
- Declarations: We call classes of components, directives, and pipes here. If you add the same class multiple times, it will give errors.
- Imports: Here, we load additional modules such as FormsModule, RouterModule, CommonModule, or any other custom module.
- Providers: We use injectable services here. It fetches data from the API.
- Exports: A set of declarable components, directives, pipes, and modules that an importing module can use within any component template.
- Bootstrap: Here we add the component that will be the root component or main application view, which is the host for all other application views.
How to create a custom module in Angular
We can also create a custom module and organize your code in that module. Below are the CLI commands to create a module.
The CLI command for generating a Module
1 | ng generate module module-name |
The CLI command for generating a Module with Routing
1 | ng generate module module-name --routing |
Sorter CLI command for generating a module.
1 | ng g m module-name |
ng – Angular
g – Generate
m – Module
In the section above, we learned how to create a module with several components, services, and pipes.