Mean Stack Technology Lab
Mean Stack Technology Lab
MEAN Stack
Mean stack stands for Mongo DB, Express JS, Angular, and Node JS. It is a set of these technologies
that are used to develop each end of a web application. Further details about these technologies are
given as follows:
Angular : Angular is client side framework which is used to develop User Interface.
Node JS :Node JS is a run time environment of JavaScript which allows developer to execute
JS code directly in console
Angular handles the implementation of the user interface (UI). Whenever the UI requires data, it
sends a request to the server, prompting the server to retrieve the necessary information from
MongoDB. Once the server successfully locates the required data, it sends the response back to the
client side.
Easy to learn.
1.ANGULAR INTRODUCTION
Angular: Angular is an open-source web application framework maintained by
Google and a community of developers. It is designed to build dynamic and
interactive single-page applications (SPAs) efficiently. With Angular, developers
can create robust, scalable, and maintainable web applications.
History:
Angular, initially released in 2010 by Google, has undergone significant
transformations over the years. The first version, AngularJS, introduced
concepts like two-way data binding and directives. However, as web
development evolved, AngularJS faced limitations in terms of performance and
flexibility.
Prerequisites:
TypeScript
HTML
CSS
JavaScript
Why Angular?
JavaScript is the most commonly used client-side scripting
language. It is written into HTML documents to enable
interactions with web pages in many unique ways.
Step 2: Create a New Angular Project: Use Angular CLI to create a new Angular
project. Navigate to the desired directory and run:
ng new my-angular-app
Step 3: Navigate to the Project Directory: Move into the newly created project
directory:
Folder Structure:
cd my-angular-app
Step 4: Serve the Application: Launch the development server to see your app
in action:
ng serve
OUTPUT :
3.INTRODUCTION TO COMPONENTS
Angular components are the building blocks of a UI in an Angular application.
These components are associated with a template and are a subset of
directives. The above image shows the classification tree structure. A root
component, the App Component, branches out into other components,
creating a hierarchy.
Creating a Component in Angular 10:
To create a component in any angular application, follow the below steps:
Get to the angular app via your terminal.
Create a component using the following command:
ng g c <component_name>
OR
ng generate component <component_name>
Using a component in Angular :
Go to the component.html file and write the necessary HTML code.
Go to the component.css file and write the necessary CSS code.
Write the corresponding code in component.ts file.
Run the Angular app using ng serve –open
OUTPUT :
4. TEMPLATES ,INTERPOLATION ,AND DIRECTIVES
A) TEMPLATES: Introduction to components and templates
A component controls a patch of screen called a view. It consists of a TypeScript
class, an HTML template, and a CSS style sheet. The TypeScript class defines
the interaction of the HTML template and the rendered DOM structure, while
the style sheet describes its appearance.
OUTPUT :
B)INTERPOLATION:
Interpolation is a way to transfer the data from a TypeScript code to an HTML
template (view), i.e. it is a method by which we can put an expression in
between some text and get the value of that expression. Interpolation basically
binds the text with the expression value
Syntax: {{expression}}
STEP1: manu.component.html
Manu.component.ts
OUTPUT :
C)DIRECTIVES:
Directives are markers in the Document Object Model(DOM). Directives can be
used with any controller or HTML tag which will tell the compiler what exact
operation or behaviour is expected. There are some directives present that are
predefined but if a developer wants he can create new directives (custom-
directive).
1. Component Directives
2. Attribute Directives(ngClass ,ngStyle ,ngModel)
3. Structural Directives(ngIf,ngSwitch,ngFor)
1.Component Directives :
Example:
2.Structural Directives:
i)ngFor:
Component2.component.ts :
Component2.component.html :
Component2.component.css:
OUTPUT :
ii)ngIf :
app.component.ts :
App.component.html:
OUTPUT :
iii)ngIf-else :
component1.component.ts :
Component1.component.html :
OUTPUT :
iv)ngSwitch :
component1.component.ts :
Component1.component.html :
OUTPUT :
3.Attribute Directives :
ngClass and ngStyle :
component2.component.ts :
Component2.component.html :
OUTPUT :
.html :
OUTPUT :
B)PIPES: The pipe() function in Angular is used to chain multiple operators
together to transform data. It receives an input value works on it and gives
back a modified result. You can recognize pipes in your template expressions by
the pipe symbol ( | ).
1. Built-in Pipes
Angular comes equipped with built in pipes that handle a variety of common
formatting duties.
<p>Today's date: {{ today | date:'mediumDate' }}</p>
DatePipe-The DatePipe is utilized for date formatting. It enables us to
present dates, in styles like short, medium and full. For example we can
utilize to exhibit the form of the date.
{{ myDate | date: "short" }}
UpperCasePipe - This tool changes a text to capital letters. It requires a
text, as input. Gives back the text in all capital letters.
{{ myString | uppercase }}
LowerCasePipe - This particular pipe is utilized for changing a string to
lowercase. Its functionality resembles that of the UpperCasePipe except
it changes the string to lowercase instead.
{{ myString | lowercase }}
CurrencyPipe - This tool helps to convert numbers into currency values.
You input a number. It gives back a string showing the number, in the
desired currency format.
{{ myNumber | currency: "USD" }}
App.component.html :
App.component.ts :
2.Customized Pipes:
Creating custom pipes in angularis useful when you need to apply custom
data transformations that aren’t covered by the built-in pipes .
i)Reverse String Pipe :
reverse.pipe.ts :
export class ReversePipe implements PipeTransform{
transform(value:string):string{
return value.split(‘’).reverse().join(‘ ‘);
}}
App.component.html :
<p> {{‘Angular’ |reverse}}</p>
ii)Mask String Pipe :
mask.pipe.ts :
export class MaskPipe implements PipeTransform{
transform(value :string,visibleDigits:number):string{
const masked =value.slice(0,-visibleDigits).replace(/./g,’*’);
const masked +visible;
}}
App.component.html:
<p>{{‘12345678123456778’ | mask:4}}</p>
OUTPUT :
6.MORE ON COMPONENTS
In Angular,communication between parent and child components can be
achieved using different methods,depending on the direction of
communication.
Create two components name them as parent component and child
component.
1)Communication from Parent to Child:
parent.component.ts
Convert ParentComponent to a standalone component:
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-parent',
standalone: true,
imports: [CommonModule, ChildComponent], // Import ChildComponent
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentMessage: string = 'Hello from Parent Of Neelima Hima Bindu';
message: string = '';
receiveMessage(message: string) {
this.message = message;
}
}
parent.component.html
<app-child [rakiBhai]="parentMessage"
(messageEmitter)="receiveMessage($event)"></app-child>
<p>{{ message }}</p>
child.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() rakiBhai: string = '';
@Output() messageEmitter = new EventEmitter<string>();
sendMessage() {
this.messageEmitter.emit('Neelima Hima Bindu from Child!');
}
}
child.component.html
<h2>{{ binnu }}</h2>
<button (click)="sendMessage()">Send Message to Parent</button>
2)Communication from Child to Parent:
To send data from the child component to the parent component,Angular
uses @Output() along with EventEmitter.
Child.component.ts :
Export class ChildComponent{
@Input() fromparent:string=”;
@Output() messageEvent=new EventEmitter<string>();
sendMessage()
{
this.messageEvent.emit(“this is from child”);
}}
Child.component.html :
<p>child works!</p>
<h1>{{fromparent}}</h1>
<button (click)=”SendMessage()”>click me</button>
Parent.component.ts :
export class ParentComponent{
parentmsg:string=”hi csd from parent”:
message:string=’ ‘;
receiveMessage(message:string){
this.message=message;
}}
Parent.component.html :
<p>parent works !</p>
<app-child
(messageEvent)=”receiveMessage($event)”[fromparent]=”parentmsg”></app-
child>
<h2>{{message}}</h2>
OUTPUT :
8.ANGULAR FORMS
Forms:
Angular provides two approaches for handling forms: Template-driven
forms and Reactive forms. Both approaches offer powerful validation
and custom control support.
OUTPUT :
Reactive forms:
OUTPUT :
9.DEPENDENCY INJECTION(DI)
Services
Services are classes that provide reusable functionality and can be injected
into other components, directives, or services.
Dependency Injection (DI) is the mechanism Angular uses to inject instances of
services into components or other services automatically.
Steps:
1. Create a Service.
2. Inject the Service into a Component using Angular's DI system.
ng generate service auto
@NgModule({
declarations: [AppComponent],
imports: [HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule {}
Inject HttpClient: In the service or component where you want to fetch data,
inject HttpClient and use it to make HTTP requests.
b. Making a GET Request
Here’s an example of a simple service that fetches data from an API using a GET
request.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
@Component({
selector: 'app-root',
template: `<ul><li *ngFor="let post of posts">{{ post.title }}</li></ul>`
})
export class AppComponent implements OnInit {
posts: any[] = [];
ngOnInit(): void {
// Subscribe to the observable to fetch data
this.dataService.getPosts().subscribe((data) => {
this.posts = data;
});
}
}
2. Navigation and Routing Basics
Angular provides Routing for navigation between different views in your
application. With routing, you can navigate between different components
based on the URL.
a. Setting Up Routing
To use routing in Angular:
1. Import RouterModule: You need to configure the routes in the app-
routing.module.ts.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { PostComponent } from './post/post.component';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The HomeComponent will be displayed when the user navigates to the
root (/).
The PostComponent will display when the user visits /post/:id, where id
is a dynamic parameter (e.g., /post/1)
2. Using RouterLink for Navigation: Use routerLink in your template to
navigate between components.
<!-- In a component template -->
<a routerLink="/post/1">Go to Post 1</a>
b. Using the ActivatedRoute to Retrieve Route Parameters
To retrieve the dynamic parameter (id) from the route, use ActivatedRoute in
your component.
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-post',
template: `<h2>Post ID: {{ postId }}</h2>`
})
export class PostComponent implements OnInit {
postId: number;
ngOnInit(): void {
// Retrieve the route parameter using ActivatedRoute
this.route.paramMap.subscribe(params => {
this.postId = +params.get('id'); // Get 'id' as a number
});
}
}
c. Navigating Programmatically with Router
You can also navigate programmatically in your component using Angular’s
Router.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
template: `<button (click)="goToPost()">Go to Post 1</button>`
})
export class HomeComponent {
goToPost() {
this.router.navigate(['/post', 1]); // Navigate to /post/1
}
}
3. Handling Navigation Events
You can listen to route changes and take action based on the navigation
lifecycle using Router.events.
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
@Component({
selector: 'app-root',
template: `<h1>App</h1>`
})
export class AppComponent implements OnInit {
ngOnInit(): void {
// Subscribe to router events
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
console.log('Navigation started:', event.url);
}
});
}
}
11. NODEJS INTRODUCTION
Express.js (Framework for Node.js):
o While Node.js itself is just a runtime, you’ll often use frameworks like
Express.js to simplify building web applications. Express makes routing,
middleware, and request handling more straightforward.
Example with Express.js
Express.js is a minimal web framework that runs on top of Node.js, simplifying
web server development.
1. Install Express:
o First, you’ll need to initialize a Node.js project by running npm init in
your project folder.
o
Then, install Express:
npm install express
Create a basic Express server: const express = require('express'); const app =
express();
15.BUFFERS,STREAMS,EVENTS
1. Buffers (Handling Binary Data)
Buffers are used to handle raw binary data directly in memory, making them
useful for working with files, network sockets, and streams.
Buffers store binary data and can be converted to a string using .toString().
2. Streams (Handling Large Data Efficiently)
Streams allow you to process data in chunks instead of loading everything into
memory, making them ideal for handling large files or network requests.
Types of Streams
Readable (e.g., reading a file)
Writable (e.g., writing to a file)
Duplex (both readable & writable, e.g., sockets)
Transform (modifies data, e.g., compression)
Example: Reading a File Using Streams
OUTPUT :
Step:1
Open VSCODE--- create a new folder KK----select the folder myapp ---- In myapp
folder create another folder named as models.
Inside models folder create a file named as User.js
Step2:
Inside models folder create another folder named as views----- In views folder
create a two files
1. newUser.ejs
2. users.ejs
Step 3:
Create another folder in myapp i.e., routes -- inside routes folder create a
file userRoutes.js
Step 4:
Inside myapp folder create a file i.e., .env
Step 5:
In myapp folder create another file named as app.js
Create a .env file in the root directory:
Create app.js
Output:
18. Installing the mongodb in the sytem and set the
path
In Visual Studio Code: Install Mongodb using the following command: