Features of NgModules
- Encapsulation: NgModule provides encapsulation by encapsulating components, directives, and pipes within a module, preventing naming conflicts and promoting modularity.
- Dependency Injection: NgModule facilitates dependency injection by allowing the registration of providers at the module level, making services available throughout the module and its components.
- Lazy Loading: NgModule supports lazy loading, enabling the loading of modules on-demand, thus improving application performance and reducing initial load times.
- Reusability: NgModule promotes code reusability by allowing modules to be imported into multiple feature modules, facilitating code organization and sharing across the application.
Example of NgModule :
Step 1: Install the angular cli using the following command.
npm install -g @angular/cli
Step 2: Create a new angular App
ng new my-angular-project
Folder Structure:
The updated Dependencies in package.json file will look like:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Code Example: Ctreate the required files and add the following codes.
// src/app/app.component.html
<h1>Hello {{Name}}</h1>
//src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-angular-project';
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
To start the application run the following command.
ng serve
Output:
Differece between JavaScript Modules & NgModule
Modules play an important role in structuring and organizing the code of Javascript and Angular.js. They help us to use the code efficiently. Majorly NgModule in Angular.js and Modules in Javascript are widely used in different scenarios.
In this article, We will learn about Modules and their importance in Angular.js and Javascript.
Table of Content
- Javascript Modules
- Features of JavaScript Modules
- NgModules
- Features of NgModules
- Difference between NgModule and JavaScript Modules
- Conclusion
Contact Us