Introduction To Angular Modules

Introduction To Angular Modules

In this article, we will learn about Angular Modules. Components, Templates, Directives, Pipes, and Services are the building blocks of Angular Applications. To make a complete application, we need a lot of these pieces. Managing these blocks becomes more complex as the application develops in size. Angular provides a simple and effective approach to organizing these chunks using Angular modules (Also known as ngModule).

Components, Templates, Directives, Pipes, and Services are the building blocks of Angular Applications. To make a complete application, we need a lot of these pieces. Managing these blocks becomes more complex as the application develops in size. Angular provides a simple and effective approach to organizing these chunks using Angular modules (Also known as ngModule).

What is Angular Module

The Angular module (also known as ngModule) aids in the organization of application components into functional units. Each block focuses on offering a specific feature or capability.

A specific feature must be implemented in the Angular module. That Module will include the Components, Directives, and Services that implement that feature.

Separation of issues is aided by the modular design. Keep the features in the same order. It's simple to maintain the code. Allows the code to be reused more easily.

Modules are the foundation of the Angular framework. The main Angular module, @angular/core, implements Angular's basic functionality, as well as low-level services and utilities.

Forms, HTTP, and Routing are implemented as independent Feature modules called FormsModule, HttpClientModule, and RoutingModule, respectively.

JavaScript Modules vs. NgModules

JavaScript Modules

The JavaScript Language includes JavaScript Modules, which are sometimes known as JS modules, ES modules, or ECMAScript modules. A file is used to hold the JS Modules. Each file has exactly one module, and each module has exactly one file. These modules are made up of little pieces of code that can be reused. They produce a value that can be imported and used by another module.

The SomeComponent is exported by the Javascript Module below.

export class SomeComponent { 
   //do something
}

Another JavaScript Module that imports and uses the SomeComponent is the SomeOtherComponent.

import { SomeComponent } from './some.component';
 
export class SomeOtherComponent { 
   /do some other thing
}

How to Create an Angular Module

The Components, Pipes, and Directives that the Angular Module maintains must be declared. The Angular Modules are created by using the ngModule decorator.

ngModule

The NgModule() decorator takes a single metadata object whose properties describe the module and returns it. The following are the most essential characteristics.

@NgModule({
  declarations: [  ],
  imports:      [  ],
  providers:    [  ],
  exports:      [  ],
  bootstrap:    [  ],
  entrycomponents: [ ]
})

Declarations array

This is where this NgModule's components, directives, and pipes are declared.

Only those that belong to this module should be added. The Component can't be in two modules at the same time.

It is not necessary to declare the services here. The Angular Providers array defines them.

Providers array

Here you can add the services that you want to add to the global collection of services. Dependency injection makes the services available for injection.

Remember :
  • Components, Directives, and Pipes all have declarations.
  • Services are provided by Providers.
  • The breadth of services is global. Services added to the Providers array are injectable across the application.

Imports array

If you want this ngModule to have any features or functionality, you must import those modules here. This module can use any of the components, directives, and pipes specified and exported in that module.

Exports array

If you wish other modules to use this NgModule's component, pipes, or directives, you must specify them here.

Remember:
When other ngModules imports this module, just the components declared here are visible.

Bootstrap

This is where you specify the main component of this module, which must be loaded when the module is loaded.

If you're the initial module (also known as the root module) loaded when the Angular App starts, this is a necessity. The root module is responsible for loading the first view, which is done by providing the component here.

If the module isn't the root module, leave this field empty.

EntryComponents

This is where dynamically loaded components must be defined.

When angular, the components are loaded.
  • The Component Selector is located in the HTML.
  • The bootstrap array declares this.
  • In the root definition, it's stated.

If none of the above apply to your component, it must be specified in EntryComponent so that Angular knows where to look for it and compile it.

The image below should demonstrate how the ngModule metadata works.

Module or ngModule Decorator In Angular



Angular Module Example

To show the use of Angular Modules, let's develop an example application with many modules.

Create the application using the following command:

ng new --routing  --style css ModuleDemo

Run the application with npm start to ensure everything is working properly.

npm start

There are two modules in the app. AppModule and AppRoutingModule, for example.

Routing Module

The AppRoutingModule is an Angular Module that describes the application Routes in detail.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
const routes: Routes = [];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

There are no components, pipelines, or directives in this module. As a result, nothing needs to be declared in the declaration array.

Because this Module does not include any services, the provider's array is likewise unnecessary.

Because the Angular RouterModule is required for the routing to function, it has been imported. The routes are required for the RouterModule to function, thus they are supplied to it in the forRoot method.

Only one instance of the RouterModule's services is required by the application. However, every Angular module that has its own routes must import RouterModule and register the routes.

This is a problem that Angular provides an excellent solution to. Only if you use the forRoot technique do the Services get registered. The technique forRoot must be used.

Root Module

The first module to be loaded is Root Module, which is also known as AppModule and is produced automatically by the Angular CLI.

The AppModule's auto-generated code is as follows. The @NgModule decorator is applied to the class.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

There are no pipes or directives in the AppModule because it just has one component, AppComponent. As a result, the declaration array just contains AppComponent.

The additional modules used by this module should be listed in the import information. As a result, the BrowserModule, which is an Angular Library, gets imported. It also needs Routes, therefore we're bringing in AppRoutingModule.

There are no services defined in the AppModule. As a result, the provider's array is blank.

Finally, we need the AppComponent to be loaded when the app starts, so we define it in the bootstrap array.

Creating a Module

Let's add another Module to our previously mentioned application.

Make a folder called home in the src/app folder.

Components

Let's add three more elements. HomeComponent, AboutUsComponent, and ContactUsComponent are all components.

Under the home folder, make a folder called pages. Make a three-folder structure under the pages about us, contact us, and home.

Add the following code under the home/pages/aboutus/about-us.component.ts file.

import { Component } from '@angular/core';
 
@Component({
    templateUrl: './about-us.component.html',
})
export class AboutUsComponent
{
}

Add the following code under the home/pages/aboutus/about-us.component.html file.

<h1> About Us Page</h1>


home/pages/contactus/contact-us.component.ts

import { Component } from '@angular/core';
 
@Component({
    templateUrl: './contact-us.component.html',
})
export class ContactUsComponent
{
}

Add the following code under the home/pages/contactus/contact-us.component.html file.

<h1> Contact Us</h1>

home/pages/home/home.component.ts

import { Component } from '@angular/core';
 
@Component({
    templateUrl: './home.component.html',
})
export class HomeComponent
{
}

Add the following code under the home/pages/home/home.component.html file.

<h1> Welcome To Module Demo</h1>

Add the following code under the home/pages/index.ts file.

export * from './aboutus/about-us.component';
export * from './contactus/contact-us.component';
export * from './home/home.component';

Home Module

Now that we have all of our components, we can build the HomeModule.

Create a home.module.ts file in the home folder and put the following code.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
 
import { AboutUsComponent,ContactUsComponent,HomeComponent } from './pages';
 
const routes: Routes = [
  {   path: '',   component: HomeComponent   },
  {   path: 'home',   component: HomeComponent   },
  {   path: 'contactus',   component: ContactUsComponent   },
  {   path: 'aboutus',   component: AboutUsComponent   },
];
 
@NgModule({
  declarations: [AboutUsComponent,ContactUsComponent,HomeComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
  ],
  providers: [],
})
export class HomeModule { }

We use @NgModule to indicate to Angular that the HomeModule class is an Angular Module.

Next, declare the three components we've made using the declarations array.

We leave the provider's array empty because the HomeModule does not expose any services.

The Routes are kept in the module itself. A separate routing module, similar to the AppRoutingModule, can be created. This will aid in the clean-up of the HomeModule code.

HomeModule depends on CommonModule, thus it's included in the imports list. The RouterModule module is loaded, and routes are created using the forChild method (routes). The routes were registered by forChild, but no services were registered.

Add the following code under the home/index.ts file.

export * from './pages';
export * from './home.module';

Using HomeModule in AppModule

The HomeModule must now be imported into the AppModule. Import the HomeModule first.

import { HomeModule} from './home';

Next, add HomeModule to the @ngModule's imports information.

imports: [
  BrowserModule,
  AppRoutingModule,
  HomeModule
],

After that, we'll use the HomeModule's Components. Add the following code to the app.component.ts file.

<ul>
  <li>
    <a class="navbar-brand" routerlink="/">Home</a>
  </li>
  <li>
      <a class="navbar-brand" routerlink="/aboutus">About</a>
  </li>
  <li>
    <a class="navbar-brand" routerlink="/contactus">Contact</a>
  </li>
</ul>

<router-outlet></router-outlet>

All we've done is make a menu item with them routerLink.

To app.component.css, copy the following CSS.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333333;
}
 
li {
    float: left;
}
 
li a {
    display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
 
li a:hover {
    background-color: #111111;
}

Finally, run the application.

Conclusion

We covered what Angular Modules are and how to make an Angular Module in this article.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post