Skip to main content

What Is Modules (@NgModule decorator)?

The NgModule is a TypeScript class marked by the @NgModule decorator.

The NgModule is a class and work with the @NgModule decorator function and also takes a metadata object that tells Angular how to compile and run module code.

The Angular module helps you to organize an application into associative blocks of functionality.
An angular module represents a core concept and plays a fundamental role in structuring Angular applications.

The NgModule is used to simplify the ways you define and manage the dependencies in your applications and also you can consolidate different components and services into associative blocks of functionality.

Every Angular application should have at least one module and it contains the components, service providers, pipes and other code files whose scope is defined by the containing NgModule.

The purpose of the module is to declare everything you create in Angular and group them together.

Every application has at least one Angular module, the root module that you bootstrap to launch the application. The Angular root module is called AppModule.
The module is a way to organize your dependencies for
1.          Compiler
2.          Dependency Injection

A module can import other modules and can expose its functionality to other modules. The modules can be loaded eagerly when the application starts or lazy loaded asynchronously by the router.

The angular loads a root dynamically because it is bootstrapped in the Angular Module.
An Angular app needs at least one module that serves as the root module.

You can use CLI commands to generate an app, the default AppModule is as follows –
ng new yourApp


The above CLI command is used to create a new Angular project and this CLI command automatically creates several folders and files which are necessary for project development, testing, and configuration and so on.

The Angular CLI (Command Line Interface) is a tool to initialize, develop, scaffold and maintain Angular applications. To use this we need to install it first and it should be installed globally on your machine.

npm install -g @angular/cli


The following is an example of specifying a NgModule -
//JavaScript imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';

//AppModule class with @NgModule decorator.
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]  // bootstrapped entry component
})
export class AppModule { }


What are the @NgModule Metadata Properties?
The @NgModule decorator identifies AppModule as a NgModule class.
The @NgModule takes a metadata object that tells Angular how to compile and launch the application.

The NgModule’s important metadata properties are as follows –
1.          providers
2.          declarations
3.          imports
4.          exports
5.          entryComponents
6.          bootstrap
7.          schemas
8.          id

The @NgModule class with the decorator and metadata properties -
@NgModule({
  providers?: Provider[]
  declarations?: Array<Type<any> | any[]>
  imports?: Array<Type<any> | ModuleWithProviders | any[]>
  exports?: Array<Type<any> | any[]>
  entryComponents?: Array<Type<any> | any[]>
  bootstrap?: Array<Type<any> | any[]>
  schemas?: Array<SchemaMetadata | any[]>
  id?: string
})


Let understand in detail about NgModule metadata is as follows-

Providers – A list of dependency injection (DI) providers and it defines the set of injectable objects that are available in the injector of this module.

Declarations - A list of declarable classes, components, directives, and pipes that belong to this module. The compiler throws an error if you try to declare the same class in multiple modules.

Imports - A list of modules and it used to import the supporting modules like FormsModule, RouterModule, CommonModule, or any other custom made feature module.

Exports - A list of declarable components, directives, pipes, and modules that an importing module can be used within a template of any component.

EntryComponents - A list of components that should be compiled when this module is defined. By default, an Angular app always has at least one entry component, the root component, AppComponent.

A bootstrapped component is an entry component that Angular loads into DOM during the application launch and other root components loaded dynamically into entry components.

Bootstrap – A list of components that are automatically bootstrapped and the listed components will be added automatically to entryComponents.

Schemas - Defines a schema that will allow any non-Angular elements and properties.

Id – The Id used to identify the modules in getModuleFactory. If left undefined, the NgModule will not be registered with getModuleFactory.

What is the difference between declarations, providers, and import in NgModule?
For more information, see the above question - What Are the @NgModule Metadata Properties?

Why use multiple NgModules?
Multiple NgModules provides some potential benefits.

Actually, the modules help you to organize an application into associative blocks of functionality.

First one is organizing an application code. If you are putting around 99 resource files in the default app module and see the happing.

And the second one is - It opens the possibility of lazy loading via the router.

What Are the Purpose of @NgModule?
The NgModule is used to simplify the ways you define and manage the dependencies in your applications and also you can consolidate different components and services into cohesive blocks of functionality.

The @NgModule metadata divided into three categories as follows.
1.          Static
2.          Runtime
3.          Composability/Grouping

Static – It is compiler configuration and configured via the declarations array.

Runtime - It is injector configuration and configured via the provider’s array.

Composability/Grouping – Introducing NgModules together and configured via the imports and exports arrays.

The following is an example of specifying a NgModule metadata -
@NgModule({
  // Static, This is the compiler configuration
  declarations: [], //declarations is used for configure the selectors.
  entryComponents: [], //entryComponents is used to generate the host factory.

  //Runtime or injector configuration
  providers: [], // providers is used for runtime injector configuration.

  //Composability and Grouping
  imports: [], // imports used for composing NgModules together.
  exports: [] //A list of declarations components, directives, and pipes classes that an importing module can use.
})


What Types of NgModules?
There are four types of NgModules –
1.          Features Module
2.          Routing Module
3.          Service Module
4.          Widget Module
5.          Shared Module
Features Module – The feature modules are NgModules for the purpose of organizing an application code.

Routing Module – The Routing is used to manage routes and also enables navigation from one view to another view as users perform application tasks.

Service Module – The modules that only contain services and providers. It provides utility services such as data access and messaging. The root AppModule is the only module that should import service modules. The HttpClientModule is a good example of a service.

Widget Module - The third party UI component libraries are widget modules.

Shared Module – The shared module allows you to organize your application code. You can put your commonly used components, directives, and pipes into the one module and use whenever required to this module.

What Is Feature Modules?
What Are the Types of Feature Modules?
The feature modules are modules that goal of organizing an application code. It also helps you partition the app into focused areas when you can do everything within the root module.

There are five types of feature modules which are the following-
1.          Domain Feature Modules
2.          Routed Feature Modules
3.          Routing Modules
4.          Service Feature Modules
5.          Widget Feature Modules

Routed Feature Module - Routed feature modules are domain feature modules that components targets of router navigation routes.

A lazy-loaded routed feature module should not be imported by any module.

Routed feature modules do not export anything because their components never appear in the template of an external component.

Routing Module - A routing module provides routing configuration for another module and the routing module focus on the following.

1.          Defines Routes
2.          Adds Router Configuration to the module's imports
3.          Adds service providers to the module's providers
4.          A routing module doesn’t have its own declarations. The components, directives, and pipes are the responsibility of the feature module and not the routing module.
A routing module should only be imported by its companion module.

Service Feature Module - Service modules provide utility services and used to communicate with the server. The HttpClientModule is a great example of a service module.

The root AppModule is the single module that should import service modules.

Domain Feature Module - Domain feature modules deliver a user experience dedicated to a special application domain as like editing a customer and so on.

Widget Feature Module - A widget module makes components, directives, and pipes available to external modules.

The third party UI components and libraries are widget modules.
Import widget modules in any module whose component templates need the widgets.

Why you use BrowserModule, CommonModule, FormsModule, RouterModule, and HttpClientModule?

BrowserModule – The browser module is imported from @angular/platform-browser and it is used when you want to run your application in a browser.

CommonModule – The common module is imported from @angular/common and it is used when you want to use directives - NgIf, NgFor and so on.

FormsModule – The forms module is imported from @angular/forms and it is used when you build template driven forms.

RouterModule – The router module is imported from @angular/router and is used for routing RouterLink, forRoot, and forChild.

HttpClientModule –The HttpClientModule is imported from @angular/common/http and it used to initiate HTTP request and responses in angular apps. The HttpClient is more modern and easy to use the alternative of HTTP.

What are the differences in NgModules and JavaScript Modules?

NgModules vs. JavaScript Modules -
The NgModule is a TypeScript class decorated with @NgModule Decorator - is a fundamental feature of Angular.

JavaScript also has its own module system for managing collections of JavaScript objects. It is completely different from the NgModule system.

In JavaScript, each file is a module and all objects defined in the file belong to that module. The module declares some objects to be public by marking them with the export keyword.

Other JavaScript modules use import statements to access public objects from other modules.

The following is an example of specifying an export and import statements -
export class AppComponent {
   //...
}

After export your class, you can import that file code in another file.
import { AppComponent } from './app.component';


Both the JavaScript and Angular use modules to organize applications code.
By Anil Singh | Rating of this article (*****)

Popular posts from this blog

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVADOR

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin

React | Encryption and Decryption Data/Text using CryptoJs

To encrypt and decrypt data, simply use encrypt () and decrypt () function from an instance of crypto-js. Node.js (Install) Requirements: 1.       Node.js 2.       npm (Node.js package manager) 3.       npm install crypto-js npm   install   crypto - js Usage - Step 1 - Import var   CryptoJS  =  require ( "crypto-js" ); Step 2 - Encrypt    // Encrypt    var   ciphertext  =  CryptoJS . AES . encrypt ( JSON . stringify ( data ),  'my-secret-key@123' ). toString (); Step 3 -Decrypt    // Decrypt    var   bytes  =  CryptoJS . AES . decrypt ( ciphertext ,  'my-secret-key@123' );    var   decryptedData  =  JSON . parse ( bytes . toString ( CryptoJS . enc . Utf8 )); As an Example,   import   React   from   'react' ; import   './App.css' ; //Including all libraries, for access to extra methods. var   CryptoJS  =  require ( "crypto-js" ); function   App () {    var   data

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan You was inspired by Angular and the Vue.js 2 components looks like -

Encryption and Decryption Data/Password in Angular

You can use crypto.js to encrypt data. We have used 'crypto-js'.   Follow the below steps, Steps 1 –  Install CryptoJS using below NPM commands in your project directory npm install crypto-js --save npm install @types/crypto-js –save After installing both above commands it looks like  – NPM Command  1 ->   npm install crypto-js --save NPM Command  2 ->   npm install @types/crypto-js --save Steps 2  - Add the script path in “ angular.json ” file. "scripts" : [                "../node_modules/crypto-js/crypto-js.js"               ] Steps 3 –  Create a service class “ EncrDecrService ” for  encrypts and decrypts get/set methods . Import “ CryptoJS ” in the service for using  encrypt and decrypt get/set methods . import  {  Injectable  }  from   '@angular/core' ; import   *   as   CryptoJS   from   'crypto-js' ; @ Injectable ({    providedIn:   'root' }) export   class   EncrDecrS