What is an Angular Module?

Posted by

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.

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:

  1. Declarations: We call classes of components, directives, and pipes here. If you add the same class multiple times, it will give errors.
  2. Imports: Here, we load additional modules such as FormsModule, RouterModule, CommonModule, or any other custom module.
  3. Providers: We use injectable services here. It fetches data from the API.
  4. Exports: A set of declarable components, directives, pipes, and modules that an importing module can use within any component template.
  5. 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

The CLI command for generating a Module with Routing

Sorter CLI command for generating a module.

ng – Angular

g – Generate

m – Module

In the section above, we learned how to create a module with several components, services, and pipes.

Leave a Reply

Your email address will not be published. Required fields are marked *