0% found this document useful (0 votes)
7 views115 pages

Aditya College Engineering Vision & Mission

Uploaded by

victoriajoshna97
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views115 pages

Aditya College Engineering Vision & Mission

Uploaded by

victoriajoshna97
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COLLEGE OF ENGINEERING AND TECHNOLOGY

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY

INSTITUTE VISION AND MISSION

VISION:
To induce higher planes of learning by imparting technical education with
✓ International standards
✓ Applied research
✓ Creative Ability
✓ Value based instruction and to emerge as a premiere institute

MISSION:

Achieving academic excellence by providing globally acceptable technical


education by forecasting technology through
✓ Innovative Research And development
✓ Industry Institute Interaction
✓ Empowered Manpower
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DEPARTMENT VISION AND MISSION

VISION:

To become a center for excellence in Computer Science and Engineering


education and innovation.

MISSION:

• Provide state of art infrastructure


• Adapt skill-based learner centric teaching methodology
• Organize socio cultural events for better society
• Undertake collaborative works with academia and industry
• Encourage students and staff self-motivated, problem-solving individuals
using Artificial Intelligence
• Encourage entrepreneurship in young minds.
[Link] DATE NAME OF THE EXPERIMENT PAGENO REMARKS
1a 04-07-2025 Observe the link [Link] on which
the mCart application is running. Perform the below
Activities to understand the features of the application.
1b 04-07-2025 Create a new component call ed hello and rendering Hello
Angular on the page.
1c 04-07-2025 Add an event to the hello component template and when it
is clicked, it should change the courseName.
2a 16-07-2025 Create a login form with username and [Link]
the user enters the correct credentials, it should render a
"Welcome<>"message otherwise it should render "Invalid
Login!!! Please try again..." message.
2b 16-07-2025 Creating a courses array and rendering it in the template
using ngFor directive in a list format.
2c 16-07-2025 Display the correct option based on the value passed to
ngSwitch directive.
2d 16-07-2025 Create a customstructural directive called 'repeat' which
should repeat the element given a number of times.
3a 22-07-2025 Apply multiple CSS properties to a paragraph in a
component using ngStyle.
3b 22-07-2025 Applying multiple CSS classes to the text using ngClass
directive
3c 22-07-2025 Create an attribute directive called 'showMessage' which
should display the given message in a paragraph when a
user clicks on it and should change the text color to red.
4a 19-08-2025 Binding image with class property using property binding.
4b 19-08-2025 Binding colspan attribute of a table element to the class
property.
4c 19-08-2025 Binding an element using inline style and user actions like
entering text in input fields.
5a 28-08-2025 Display the productcode in lowercase and productname in
uppercase using built-in pipes.
5b 28-08-2025 Apply built-in pipes with parameters to displayproduct
details.
5c 28-08-2025 LoadCourseslist Component in the rootcomponent when a
user clicks on the View courses list button.
6a 02-09-2025 Creating an AppComponent that displays a dropdown with a
list of courses as values in it. Create another component
called the Courses List component and load it in
AppComponent which should display the coursedetails.
When the user selects a course from the dropdown,
corresponding course details should be loaded.
6b 02-09-2025 Create an AppComponent that loads another component
called the courses List component. Create another
Component called CoursesList Component which should
display the courses list in a table along with a register Button
in each [Link] a user clicks on the register button, it
should send that courseName value back to AppComponent
where it should display the registration
successful message along with courseName.
6c 03-09-2025 Apply Shadow DOM and None encapsulation modes to
components.
6d 03-09-2025 Override component life-cycle hooks and logging the
corresponding messages to understand the flow.
7a 18-09-2025 Create a course registration form as a template-driven
form.
7b 18-09-2025 Create an employee registration form as a reactive form.
7c 18-09-2025 Create a custom validator for an email field in the
employee registration form ( reactive form)
8a 25-09-2025 Create a customvalidator for the email field in the course
registration form.
8b 25-09-2025 Create a BookComponent which fetches bookdetails like id,
name and displays them on the page in a list format.
Store the book details in an array and fetch the data using
a custom service.
8c 25-09-2025 Create and use an observable in Angular.
9a 09-10-2025 Create an application for ServerCommunication using
HttpClient
9b 09-10-2025 Create a customservice called ProductService in which
Httpclass is used to fetchdata stored in the JSON files.
10a 16-10-2025 Create multiple components and add routing to provide
navigation between them.
10b 16-10-2025 Consider the same example used for [Link]
guard to BooksComponent. Only after logging in, the user
should be able to access [Link] the user tries
to give the URL of Bookscomponent in another tab or
window, or if the user tries to reload the BooksComponent
page, it should be redirected to LoginComponent.
10c 16-10-2025 Apply lazy loading to BookComponent. If lazy loading is not
added to the demo,it has loaded [Link] the load time at
the bottom of the browser console. Press F12 in the browser and
click the Network tab and check the Load time.
10d 16-10-2025 Implement Child Routes to a submodule.
11a 23-10-2025 Installing MongoDB on the localcomputer,Create
MongoDB Atlas Cluster
11b 23-10-2025 Write MongoDB queries to perform CRUD operations on
document using insert(), find(), update(), remove().
12a 23-10-2025 Write MongoDB queries to Create and drop databases and
collections.
12b 23-10-2025 Write MongoDB queries to work with records using
find(), limit(), sort(), createIndex(), aggregate().
13 30-10-2025 Project
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise -1
1a) Observe the link [Link] on which the mCart application
is running. Perform the below activities to understand the features of the
application.
# Install Angular CLI globally if not already installed npm
install -g @angular/cli@16.0.0
# Create a new Angular project named 'mcart' ng
new one
# Navigate into the project folder cd
one
#Create a new component ng
generate component welcome
PROGRAM :
#[Link]
<div class="welcome-container">

<h1>Welcome to mCart!</h1>

<p>

Discover a world of amazing products


and unbeatable deals.

Join us on the journey of


shopping excellence! </p>

<button class="login-
button">Login</button
>
<footer class="footer-text">

<div>

Designed by 22MH1A05D1

</div></footer>

MEAN STACK TECHNOLOGIES MODULE-2 1 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

#[Link]
import { Component } from '@angular/core'; @Component({
templateUrl: '[Link]', styleUrls:
['[Link]']
})
export class WelcomeComponent {
public pageTitle = 'Welcome';
constructor() {
}
#[Link]
<app-welcome></app-
welcome> #To run the
Application ng serve

OUTPUT:

Designed by 22MH1A05D1

MEAN STACK TECHNOLOGIES MODULE-2 2 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

1b) Create a new component called hello and rendering Hello Angular on the page

#Create a new component


ng generate component hello
PROGRAM:
#[Link]
<p>
Hello Angular {{ courseName }}
</p>
#[Link]
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class HelloComponent implements OnInit {
courseName: string = "22MH1A05D1";
constructor() { } ngOnInit() {
}
}
#[Link]
p { color:blue; font-
size:20px;
}
#[Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './[Link]'; import { AppComponent } from
'./[Link]'; import { HelloComponent } from './hello/[Link]';

imports: [BrowserModule,AppRoutingModule],

MEAN STACK TECHNOLOGIES MODULE-2 3 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

declarations: [AppComponent, HelloComponent], providers: [],


bootstrap: [HelloComponent]
})
export class AppModule { }
#[Link]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-hello></app-hello>
</body>
</html>

OUTPUT:

1c) Add an event to the hello component template and when it is clicked, it should change the
courseName.
#Create a new component ng
generate component hello
PROGRAM :

#[Link]
<h1>Welcome</h1>

MEAN STACK TECHNOLOGIES MODULE-2 4 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<h2>Course Name: {{ courseName }}</h2>


<p (click)="changeName()">Click here to change</p>

<footer>
<div> Designed by 22MH1A05D1 </div>
</footer>

#[Link]
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello', templateUrl: "./[Link]",
styleUrls: ['./[Link]']
})
export class HelloComponent implements
OnInit { courseName = "Angular";
constructor() { } ngOnInit() {
} changeName() {
[Link] =
"TypeScript”;
}
}
#[Link]
p { color:blue; font- size:20px; } p { cursor: pointer; } p:hover { text- decoration:
}
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './app- [Link]'; import {
AppComponent } from './[Link]'; import {
HelloComponent } from './hello/[Link]';
@NgModule({
imports:
[BrowserModule,AppRoutingModule],
declarations: [AppComponent,

MEAN STACK TECHNOLOGIES MODULE-2 5 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

HelloComponent], providers: [], bootstrap:


[HelloComponent]
})
export class AppModule {}
#[Link]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-hello></app-hello>
</body>
</html>

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 6 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise -2

2a) Create a login form with username and password fields. If the user enters the correct
credentials, it should render a "Welcome <<username>>" message otherwise it should
render "Invalid Login!!! Please try again...".

PROGRAM:
#[Link]
<div *ngIf="!submitted" class="main">
<h2 class="title">Login Form</h2>

<form>
<label>Username</label>
<input type="text" #username /><br /><br />

<label for="password">Password</label>
<input type="password" name="password" #password /><br />
</form>

<button (click)="onSubmit([Link], [Link])">Login</button>


</div>

<div *ngIf="submitted" class="result">


<div *ngIf="isAuthenticated; else failureMsg">
<h4>Welcome {{ userName }}</h4>
</div>

<ng-template #failureMsg>
<h4 id="failureMsg">Invalid Login !!! Please try again...</h4>
</ng-template>

<button type="button" (click)="submitted = false">Back</button>


</div>

<footer>
Designed by 22MH1A05D1
</footer>

#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]'],

MEAN STACK TECHNOLOGIES MODULE-2 7 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

})
export class AppComponent {
isAuthenticated!: boolean; submitted
= false;

userName!: string; onSubmit(name:


string, password: string) { [Link]
= true; [Link] = name;
if (name === 'admin' && password === 'admin') {
[Link] = true;
} else {
[Link] =
false;
}
}
}
#[Link]
:host { display: flex; justify- content:
center; align-items: center; height:
100vh; font-family: 'Circular Std',
sans-serif; font- weight: bold;
} .main { width: 400px;
padding: 20px; border:
2px solid #ccc; border-
radius: 10px;
background-color:
#f8f8f8;
} label { display:
block; margin-

bottom: 8px; } input


{ width: 100%;

MEAN STACK TECHNOLOGIES MODULE-2 8 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

padding: 8px;
margin- bottom:
10px; box- sizing:
border-box;
} button {
background-color:
#1d1d1d; color:
white; padding:
10px 40px; border:
none; border-
radius: 5px; cursor:
pointer; margin-top:
20px;
}
button[type="butt
on"] { background-
color: #f44336; } h4
{ color: #333; font-
size: 40px; }
div[ngIf="submitte
d"] { margin-top:
20px; } ng- template
{ display: block;
margin-top: 10px;
}
#failureMsg {
color: #f44336;
}

MEAN STACK TECHNOLOGIES MODULE-2 9 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OUTPUT:

Welcome Sri

2b) Creating a courses array and rendering it in the template using ngFor directive
in a list format.

PROGRAM:
#[Link]
<div class="container">
<h2>Available Courses</h2>
<ul>
<li *ngFor="let course of courses; let i = index">
{{ i + 1 }} - {{ [Link] }}
</li>
</ul>

<footer> Designed by 22MH1A05D1 </footer>


</div>

#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})

MEAN STACK TECHNOLOGIES MODULE-2 10 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

export class AppComponent {


courses: any[] = [
{ id: 1, name: 'TypeScript' },
{ id: 2, name: 'Angular' },
{ id: 3, name: 'Node JS' },
{ id: 1, name: 'TypeScript' }
];
}

OUTPUT:

2C) Display the correct option based on the value passed to ngSwitch directive.
PROGRAM:
#[Link]
<div class="container">
<h3>Display Using ngSwitch Directive</h3>
<h4>Current choice is {{ choice }}</h4>

<div [ngSwitch]="choice">
<p *ngSwitchCase="1">First Choice</p>
<p *ngSwitchCase="2">Second Choice</p>
<p *ngSwitchCase="3">Third Choice</p>
<p *ngSwitchDefault>Default Choice</p>
</div>

MEAN STACK TECHNOLOGIES MODULE-2 11 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<button (click)="nextChoice()">Next Choice</button>

<footer>
Designed by 22MH1A05D1
</footer>
</div>

#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class AppComponent
{ choice = 0; nextChoice() {
[Link]++;
}
}

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 12 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

2D) Create a custom structural directive called 'repeat' which should repeat the
element given a number of times.
PROGRAM:
#Generate a directive in terminal ng generate
directive repeat

#[Link]
<div class="container">
<h2>{{ title }}</h2>
<h3>Structural Directive: *appRepeat</h3>

<p *appRepeat="9">23MH5A0510...</p>

<footer>
DesignedBy<strong>22MH1A05D1</strong>
</footer>
</div>

#[Link]
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({
selector:
'[appRepeat]'
})
export class RepeatDirective { constructor(private templateRef:
TemplateRef<any>, private viewContainer:
ViewContainerRef) { }
@Input() set appRepeat(count: number) { for
(let i = 0; i < count; i++) {
[Link]([Link]);
}}}

MEAN STACK TECHNOLOGIES MODULE-2 13 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 14 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise-3

3A) Apply multiple CSS properties to a paragraph in a component using ngStyle


PROGRAM:
#[Link]
<p [ngStyle]="{
'color': colorName,
'font-weight': fontWeight,
'font-size': fontSize,
'margin-top': marginTop,
'padding': paddingValue,
'width': width,
'line-height': lineHeight,
'font-family': fontFamily
}">
In the realm of design, every pixel tells a story, and every interaction is a chance to create
a meaningful user experience.
</p>
<footer>
<strong> Designed by 22MH1A05D1 </strong>
</footer>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent
{ colorName = 'black';
fontWeight = 'bold';
fontSize = '18px';
marginTop = '20px';

MEAN STACK TECHNOLOGIES MODULE-2 15 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

paddingValue = '10px';

width = '30%'; lineHeight = „30P‟


fontFamily = 'Segoe UI, sans-serif';
}
OUTPUT:

3B) Applying multiple CSS classes to the text using ngClass directive
PROGRAM:
#[Link]
<article class="card">
<p
class="demo-paragraph"
[ngClass]="{ 'blue-text': isBlueText, 'bold-text': isBoldText, 'wide-paragraph': isWideParagraph }"
>
From the first click to the final interaction, the design tells a story, ensuring that every
user feels not just engaged, but truly understood in the digital space.
</p>
</article>
</div>

<footer class="footer">
<span>Desined by 22MH1A05D1</span>

</footer>
#[Link]
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
imports: [CommonModule],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class App {

MEAN STACK TECHNOLOGIES MODULE-2 16 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

isBlueText: boolean = true;


isBoldText: boolean = false;
isWideParagraph: boolean = true;
}
#[Link]
.page {
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple
Color Emoji", "Segoe UI Emoji";
min-height: auto;
display: grid;
grid-template-rows: auto auto 1fr;
gap: 12px;
padding: 16px;
background: linear-gradient(180deg, #f8fafc 0%, #eef2ff 100%);
color: #0f172a;
}

.header {
display: grid;
gap: 4px;
}

OUTPUT:

3C) Create an attribute directive called 'showMessage' which should display the
given message in a paragraph when a user clicks on it and should change the text
color to red
PROGRAM:
#Generate a directive in terminal ng
generate directive message

#[Link]

import { Directive, ElementRef, Renderer2, HostListener, Input } from '@angular/core'; @Directive({


selector:
'[appMessage]',

MEAN STACK TECHNOLOGIES MODULE-2 17 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

})
export class MessageDirective {
@Input('appMessage') message!: string;
constructor(private el: ElementRef, private renderer: Renderer2) { [Link]([Link],
'cursor', 'pointer');
}
@HostListener('click') onClick() {
[Link] = [Link];
[Link]([Link], 'color', 'red');
}
}
#[Link]
<h3>Attribute Directive</h3>
<p [appMessage]="myMessage">Click Here</p>
#[Link].c:
h3 { color: #369;
font-family: Arial, Helvetica, sans-serif; font-
size: 250%;
} p { color:
#ff0080;

font-family: Arial, Helvetica, sans-serif; font-


size: 150%;
}
<footer>
Designed By<strong>22MH1A05D1</strong>
</footer>

#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:

MEAN STACK TECHNOLOGIES MODULE-2 18 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

['./[Link]']
})
export class AppComponent {
myMessage = 'Hello, I am from attribute directive';
}
OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 19 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise-4

4A) Binding image with class property using property


binding. PROGRAM:
#[Link]
<div *ngFor="let card of cardData; let i = index" class="card">
<img [src]="[Link]"
alt="Image" class="card-
image" >
<div class="card-description">
<p>{{ [Link] }}</p>
<p>{{ [Link] }}</p>
</div>
<footer>
Designed By<strong>22MH1A05D1</strong>
</footer></div>
#[Link]
.card { border: 1px solid #ccc; border-
radius: 8px; box-shadow: 0 4px 8px
rgba(0, 0, 0, 0.1); margin: 16px; padding:
16px; transition: transform 0.3s ease-in-
out; background-color: #fff; } .card-
image { width: 400px; height: 250px;
border-radius: 8px; }
.card-description { margin-top: 12px; }
.card-description p { margin: 8px 0;}
:host { display: flex; justify-
content: center; align-items:
center; height: 100vh; margin: 0;
font-family: 'Segoe UI', sans-
serif;

MEAN STACK TECHNOLOGIES MODULE-2 20 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

#[Link]
import { Component } from
'@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
}) export class AppComponent
{ cardData
=[{
imageUrl: 'assets/imgs/[Link]',
description: 'Subway Station',
cityName: 'New york City'
}, {
imageUrl: 'assets/imgs/[Link]',
description: 'Beautiful city view',
cityName: 'Tokyo'
}, {
imageUrl: 'assets/imgs/[Link]', description:
'Festival Of Lights', cityName: 'India'

}
}
OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 21 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

4B) Binding colspan attribute of a table element to the class property.


PROGRAM:
#[Link]
<table border="1">
<tr>
<td [[Link]]="colspanValue">{{ foodItems[0].name }}</td>
<td>{{ foodItems[1].name }}</td></tr><tr>
<td>{{ foodItems[2].name }}</td>
<td>{{ foodItems[3].name }}</td>
<td>{{ foodItems[4].name }}</td>
</tr></table>
<footer class="footer">
<div class="credit">
<span>Designed By</span>
<strong>22MH1A05D1</strong>
</div </footer>

#[Link]
table { width: 20%; border-collapse: collapse; margin-top: 20px;
}
th, td{
border: 1px solid #dddddd; text-align: left; padding: 8px;
}
th { background-color: #f2f2f2;
} #[Link]
import { Component } from
'@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']

MEAN STACK TECHNOLOGIES MODULE-2 22 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

// Set your desired colspan


value here foodItems = [
{ name: 'Pizza', details: 'Delicious Italian dish' },
{ name: 'Burger', details: 'Classic fast food item' },
{ name: 'Salad', details: 'Healthy and refreshing' },
{ name: 'Pasta', details: 'Italian pasta with tomato sauce' },
{ name: 'Ice Cream', details: 'Sweet and cold dessert'
}]; }
OUTPUT:

4C) Binding an element using inline style and user actions like entering text in input fields.
PROGRAM:
#[Link]
<div class="grocery-list">
<h2>Grocery List</h2>
<ul>
<li *ngFor="let item of groceryItems">
{{ [Link] }} - {{ [Link] }}</li></ul>
<div class="add-item">
<label for="itemName">Item Name:</label>
<input type="text" id="itemName" [(ngModel)]="newItemName" placeholder="Enter
item name">
<label for="itemQuantity">Quantity:</label>
<input type="number" id="itemQuantity" [(ngModel)]="newItemQuantity" placeholder="Enter

MEAN STACK TECHNOLOGIES MODULE-2 23 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

quantity">
<button (click)="addItem()">Add Item</button>
</div>
<div class="credit">Designed by 22MH1A0539</div>
</div>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
groceryItems: { name: string, quantity: number }[] = [
{ name: 'Apples', quantity: 5 },
{ name: 'Bananas', quantity: 10 },
{ name: 'Milk', quantity: 2 }
];
newItemName: string = '';
newItemQuantity: number = 0;
addItem() {
if ([Link] && [Link] > 0) {
[Link]({
name: [Link],
quantity:
[Link]
}); [Link] = '';
[Link]
= 0; }}}

#[Link]
:host { display: flex; justify-
content: center; align-items:

MEAN STACK TECHNOLOGIES MODULE-2 24 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

center; font-family: 'Segoe UI',


sans-serif;
} .grocery-list { width: 500px;
margin: 20px auto; background-
color: #fff; padding: 20px; border-
radius: 8px; box-shadow: 0 0 10px
rgba(0, 0, 0, 0.1);
} h2 { color: #333;
} ul { list-style-
type: none;
padding: 0; } li {

margin-bottom: 8px;
} .add-item {

Margin-top:
20px;
} label { display:
block; margin-
bottom: 5px; font-
weight: bold;
} input { width:
100%; padding: 8px;
margin-bottom: 10px;
box-sizing: border-
box;

#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './app- [Link]'; import {
AppComponent } from './[Link]'; import {
FormsModule } from '@angular/forms';

MEAN STACK TECHNOLOGIES MODULE-2 25 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

@NgModule({ declarations:
[AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]
})
export class AppModule {

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 26 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise -5

5A) Display the product code in lowercase and product name in uppercase using built-in pipes.
PROGRAM:
#[Link]

{{ title | titlecase}}
Product Code {{ productCode | lowercase }}
Product Name {{ productName | uppercase }}

#[Link]
table { width: 20%;
border collapse:
collapse; margin-top: 20px;
font-family: 'Segoe UI', sans-serif; }
th,
td { padding: 10px;
text-align: left;
border: 1px solid #ddd; }
th {
background-color: #f2f2f2; }
#[Link]
import { Component } from '@angular/core'; 30
@Component({
selector: 'app-root',
templateUrl: './
[Link]',
styleUrls: ['./[Link]'] })
export class
AppComponent {
title = 'product details';
productCode = 'pROD_001';
productName

MEAN STACK TECHNOLOGIES MODULE-2 27 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OUTPUT:

5B) Apply built-in pipes with parameters to display product details.


PROGRAM:
#[Link]
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<th> Product Code </th>
<td> {{ productCode | slice:5:9 }} </td>
</tr>
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
<tr>
<th> Product Price </th>
<td> {{ productPrice | currency: 'INR'}} </td>
</tr>
<tr>
<th> Purchase Date </th>
<td> {{ purchaseDate | date:'fullDate' | lowercase}} </td>
</tr>
<tr>

MEAN STACK TECHNOLOGIES MODULE-2 28 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<th> Product Tax </th>


<td> {{ productTax | percent : '.2' }} </td>
</tr>
<tr>
<th> Product Rating </th>
<td>{{ productRating | number:'1.3-5'}} </td>
</tr>
</table>
#[Link]

import { Component } from '@angular/core'; @Component({


selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class AppComponent { title
= 'product details'; productCode =
'PROD_P001'; productName =
'Apple MacBook Pro'; productPrice
= 80000; purchaseDate =
'11/11/2023';
productTax = '0.17'; productRating
= 4.92; }
#[Link]
Copy from previous experiment
#[Link]
import { BrowserModule } from '@angular/platform-
browser'; import { NgModule } from '@angular/core'; import
{ AppComponent } from './[Link]'; import

MEAN STACK TECHNOLOGIES MODULE-2 29 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

{ registerLocaleData } from '@angular/common'; import


localeFrench from '@angular/common/locales/fr';
registerLocaleData(localeFrench); @NgModule({
declarations: [
AppComponent
],
imports: [ BrowserModule
],
providers: [], bootstrap:
[AppComponent]

})
export class AppModule { }
OUTPUT:

5C) Load CourseslistComponent in the root component when a user clicks on the
View courses list button.
PROGRAM:
#Create a new component ng

MEAN STACK TECHNOLOGIES MODULE-2 30 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

generate component coursesLisT


#[Link]
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</tbody>
</table>
#[Link]
table { border-collapse:
collapse; width: 30%; } th,
td { border: 1px solid #ddd;
padding: 8px; text- align:
left; } th { background-
color: #f2f2f2;
}
#[Link] import { Component,
OnInit } from '@angular/core';
@Component({

MEAN STACK TECHNOLOGIES MODULE-2 31 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class CoursesListComponent { courses
=[
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
}
#[Link]
<h2>Popular Courses</h2>
<button (click)="show = true">View Courses list</button><br /><br />
<div *ngIf="show">
<app-courses-list></app-courses-list>
</div>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
show!: boolean;
}}

MEAN STACK TECHNOLOGIES MODULE-2 32 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 33 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise -6
6A) Creating an AppComponent that displays a dropdown with a list of courses as
values in it. Create another component called the Courses List component and load it
in
AppComponent which should display the course details. When the user selects a course
from the dropdown, corresponding course details should be loaded.
PROGRAM:
#Create a new component
ng generate component coursesList
#[Link]
<table border="1" *ngIf="[Link] > 0">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of course">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</tbody>
</table>
#[Link] import { Component,
Input } from '@angular/core';
@Component({
selector: 'app-courses-list', templateUrl:
'./[Link]', styleUrls:
['./[Link]'],
})
export class CoursesListComponent { courses

MEAN STACK TECHNOLOGIES MODULE-2 34 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

=[

{ courseId: 1, courseName: 'Node JS' },


{ courseId: 2, courseName: 'Typescript' },
{ courseId: 3, courseName: 'Angular' },
{ courseId: 4, courseName: 'React JS' },
];
course!: any[];
@Input() set cName(name: string) {
[Link] = [];
for (var i = 0; i < [Link]; i++) { if
([Link][i].courseName === name) {
[Link]([Link][i]);
}
}
}
}
#[Link] Copy
from previous experiment
#[Link]
<h2>Course Details</h2>
Select a course to view
<select #course (change)="name = [Link]">
<option value="Node JS">Node JS</option>
<option value="Typescript">Typescript</option>
<option value="Angular">Angular</option>
<option value="React JS">React JS</option></select><br /><br />
<app-courses-list [cName]="name"></app-courses-list>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root', styleUrls:

MEAN STACK TECHNOLOGIES MODULE-2 35 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 36 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

6B) Create an AppComponent that loads another component called the courses List
component. Create another component called CoursesListComponent which should
display the courses list in a table along with a register button in each row. When a user
clicks on the
register button, it should send that courseName value back to AppComponent where it
should display the registration successful message along with courseName
PROGRAM:
#Create a new component ng
generate component coursesList
#[Link]

<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td><button (click)="register([Link])">Register</button></td>
</tr>
</tbody>
</table>
#[Link]
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({
selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class CoursesListComponent {

MEAN STACK TECHNOLOGIES MODULE-2 37 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

@Output() registerEvent = new EventEmitter<string>();


courses = [
{ courseId: 1, courseName: 'Node JS' },
{ courseId: 2, courseName: 'Typescript' },
{ courseId: 3, courseName: 'Angular' },
{ courseId: 4, courseName: 'React JS' }
];
register(courseName: string) {
[Link](courseName);
}
}
#[Link] Copy
from previous experiment
#[Link]
<h2>Courses List</h2>
<app-courses-list (registerEvent)="courseReg($event)"></app-courses-list>
<br /><br />
<div *ngIf="message">{{ message }}</div>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
message!: string;
courseReg(courseName: string) {
[Link] = `Your registration for ${courseName} is successful`;
}}

MEAN STACK TECHNOLOGIES MODULE-2 38 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 39 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

6C) Apply Shadow DOM and None encapsulation modes to components.


PROGRAM:
#Create a new components ng
generate component grocery-list ng
generate component grocery- item #
grocery-

[Link]

<div>
<h2>Grocery List</h2>
<table>
<thead>
<tr>
<th>Item</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of groceryItems">
<td>
<app-grocery-item [item]="item"></app-grocery-item>
</td>
</tr>
</tbody>
</table>
</div>
#[Link]
import { Component, ViewEncapsulation } from '@angular/core'; @Component({
selector: 'app-grocery-list', templateUrl:
'./[Link]', styleUrls:
['./[Link]'],

MEAN STACK TECHNOLOGIES MODULE-2 40 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

encapsulation:
[Link],
})
export class GroceryListComponent {
groceryItems: string[] = ['Apples', 'Bananas', 'Milk', 'Bread'];
}
#[Link] div
{ margin:
20px;
} h2 { color: #333; }
table { width: 10%;
border-collapse:
collapse; margin-top:
10px;
} th, td { border: 1px
solid #ddd; padding:
8px; text-align: left;
} th
{
background-color: #f2f2f2;
}
#[Link]
<app-grocery-list></app-grocery-list>
#[Link]
<span>{{ item }}</span>
#grocery-
[Link] span {
padding: 5px; margin-
right: 5px;
}
#[Link]

MEAN STACK TECHNOLOGIES MODULE-2 41 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

import { Component, ViewEncapsulation, Input } from '@angular/core'; @Component({


selector: 'app-grocery-item',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
encapsulation: [Link],
})
export class GroceryItemComponent {
@Input() item: string = ' ';}

OUTPUT:

6D) Override component life-cycle hooks and logging the corresponding messages to
understand the flow.
#Create a new component ng
generate component child
Program :
#[Link]
<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]="data" />
<app-child [title]="data"></app-child>
</div>

MEAN STACK TECHNOLOGIES MODULE-2 42 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

#[Link]
import {
Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit,
AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-root', styleUrls:
['./[Link]'], templateUrl:
'./[Link]'
})
export class AppComponent implements OnInit, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy { data = 'Angular';
ngOnInit() { [Link]('Init');
}

ngDoCheck(): void {
[Link]('Change detected');
}
ngAfterContentInit(): void {
[Link]('After content init');
}
ngAfterContentChecked(): void { [Link]('After
content checked');
} ngAfterViewInit(): void {
[Link]('After view
init');
} ngAfterViewChecked(): void {
[Link]('After view
checked');

MEAN STACK TECHNOLOGIES MODULE-2 43 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

} ngOnDestroy():
void {
[Link]('Destroy'
);
}
}
#[Link] div { width:
500px; margin: 0 auto; margin-top:
10%; padding: 20px; border: 1px
solid #ccc; border-radius: 8px; box-
shadow: 0 0 10px rgba(0, 0, 0, 0.1);
font-family: 'Segoe UI', sans-serif;
} h1 { color: blue; } input { width: 50%;

padding: 10px;
margin-top:

10px;
box- sizing:
border- box;

} app-child {
margin-top:
20px;
}
#[Link]
<h3>Child Component</h3>
<h2>{{title}}</h2>
#[Link]
import { Component, OnChanges, Input } from '@angular/core'; @Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]']

MEAN STACK TECHNOLOGIES MODULE-2 44 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

})
export class ChildComponent implements OnChanges {
@Input() title!: string;
ngOnChanges(changes: any): void {
[Link]('changes in child:' + [Link](changes));
}
}
#[Link] s
h2 { color: red;
}
#Ensure FormsModule is present in the imports section of the [Link]
imports: [
BrowserModule,
AppRoutingModule,

FormsModule
]

OUTPUT:

MEAN STACK TECHNOLOGIES MODULE-2 45 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise -7
7 A) Create a course registration form as a template-driven form.
#Create a new component
ng generate component course-registration
Program :
#[Link]
<div class="container">
<h2>Course Registration Form</h2>
<form #registrationForm="ngForm" (ngSubmit)="onSubmit(registrationForm)">
<div class="form-group">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName" ngModel required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel required email>
</div>
<div class="form-group">
<label for="courseName">Course Name:</label>
<input type="text" id="courseName" name="courseName" ngModel required>
</div>
<div class="form-group">
<label for="Add">Address :</label>
<input type="text" id="Add" name="Add" ngModel required>
</div>
<button type="submit" [disabled]="![Link]">Submit</button>
</form>
</div>
#[Link] import
{ Component } from '@angular/core';
@Component({

MEAN STACK TECHNOLOGIES MODULE-2 46 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

selector: 'app-course-registration',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class
CourseRegistrationComponent {
onSubmit(form: any): void { if
([Link]) {

[Link]('Form submitted:', [Link]);


}
}
}
#[Link]
:host { display: flex; justify-
content: center; align-items:
center; height: 100vh; font-
family: 'Segoe UI', sans-serif;
background-color: #f7f7f7;
} .container { width: 400px; padding:
20px; border: 1px solid #ccc; border-
radius: 5px; box-shadow: 0 0 10px
rgba(0, 0, 0, 0.1); background-color:
#fff;
} h2 { text-align:
center; color: #333;
} .form-group {
margin-bottom:
20px;
} label {
display:

MEAN STACK TECHNOLOGIES MODULE-2 47 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

block; margin-
bottom: 8px;
color: #555; }
input { width:
100%;
padding: 8px;
box- sizing:
border-box;
border: 1px
solid #ccc;
border- radius:
4px; } button
{ background-
color:
#4caf50;
color: #fff;
padding: 10px
15px; border:
none; border-
radius: 4px;
cursor:
pointer; font-
size: 16px;
width: 100%;
}
button:disabl ed
{

MEAN STACK TECHNOLOGIES MODULE-2 48 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

background-
color: #ddd;
cursor: not-
allowed; }
.ng-
valid[require
d] { border-
left: 5pxsolid
#42A948; }
.ng-
invalid:not(fo
rm) { border-
left: 5px solid
#a94442;
}
#[Link]
<app-course-registration></app-course-registration>
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-
[Link]'; import { AppComponent } from
'./[Link]'; import {
CourseRegistrationComponent } from './course-
registration/[Link]';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({
declarations: [ AppComponent,
CourseRegistrationComponent
],

imports: [

MEAN STACK TECHNOLOGIES MODULE-2 49 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]
})
export class AppModule { }

output:

MEAN STACK TECHNOLOGIES MODULE-2 50 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

7B) Create an employee registration form as a reactive form.


#Create a new component ng generate
component RegistrationForm
Program :

#registration- [Link]

<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control"
formControlName="firstName"> <div
*ngIf="[Link]['firstName'].errors" class="alert alert- danger">
Firstname field is invalid.
<p
*ngIf="[Link]['firstName'].errors?.['required']"> This field
is required!
</p>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName">
<div *ngIf="[Link]['lastName'].errors" class="alert alert- danger">
Lastname field is invalid.
<p
*ngIf="[Link]['lastName'].errors?.['required']"> This field
is required!
</p>

MEAN STACK TECHNOLOGIES MODULE-2 51 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</fieldset>
</div>
<button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>
</form>
<br/>
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p>First Name: {{ [Link]('firstName')?.value }} </p>
<p> Last Name: {{ [Link]('lastName')?.value }} </p>
<p> Street: {{ [Link]('[Link]')?.value }}</p>
<p> Zip: {{ [Link]('[Link]')?.value }} </p>
<p> City: {{ [Link]('[Link]')?.value }}</p>
</div>
</div>
#[Link] import {
Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({

selector: 'app-registration-form', templateUrl:

MEAN STACK TECHNOLOGIES MODULE-2 52 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

'./[Link]', styleUrls:
['./[Link]']
})
export class RegistrationFormComponent implements OnInit {
registerForm!: FormGroup; submitted!:boolean;

constructor(private formBuilder: FormBuilder) { } ngOnInit()


{
[Link] =
[Link]({ firstName: ['',
[Link]], lastName: ['',
[Link]], address:
[Link]({
street:
[], zip:
[], city:
[] })
#[Link]
.container { width:
400px; margin: 0
auto; } form {
margin-bottom:
20px;
} .form-group {
margin-bottom:
20px;

MEAN STACK TECHNOLOGIES MODULE-2 53 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

} label { display:
block; margin-
bottom: 5px;

: #721c24; background-
color: #f8d7da; border: 1px
solid #f5c6cb; padding:
8px; margin-top: 5px;
border- radius: 4px; } .btn-
primary { background-
color: #1d1d1d; color: #fff;
border: none; padding: 10px
40px; border-radius: 4px;
cursor: pointer; } .btn-
primary:hover {
background-color: #0056b3;
} [hidden] { display:
none; } h3 { margin-
bottom: 10px;} .ng-
valid[required] {
border-left: 5px solid
#42A948; }

.ng-invalid:not(form) { border- left:


5px solid #a94442;
}
#[Link]
<app-registration-form></app-registration-form>
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './app- [Link]'; import {

MEAN STACK TECHNOLOGIES MODULE-2 54 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

AppComponent } from './[Link]';


import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import {
RegistrationFormComponent } from
'./registration-form/[Link]';
@NgModule({
declarations: [ AppComponent,
RegistrationFormComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]

Output :

Before clicking submit:

After clicking submit:

MEAN STACK TECHNOLOGIES MODULE-2 55 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

7C) Create a custom validator for an email field in the employee registration
form ( reactive form)
Program :
#[Link]
<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</fieldset>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" formControlName="email" />
<div *ngIf="[Link]['email'].errors" class="alert alert- danger">
Email field is invalid.

MEAN STACK TECHNOLOGIES MODULE-2 56 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<p*ngIf="[Link]['email'].errors?.['required']"> This field is


required!
</p>
<p *ngIf="[Link]['email'].errors?.['emailInvalid']">
{{ [Link]['email'].errors?.['emailInvalid'].message }}
</p>
</div>
</div>
<button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>
</form>
<br/>
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p>First Name: {{ [Link]('firstName')?.value }} </p>
<p> Last Name: {{ [Link]('lastName')?.value }} </p>
<p> Street: {{ [Link]('[Link]')?.value }}</p>
<p> Zip: {{ [Link]('[Link]')?.value }} </p>
<p> City: {{ [Link]('[Link]')?.value }}</p>
<p>Email: {{ [Link]('email')?.value }}</p>
</div>
</div>
#[Link]
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({
selector: 'app-registration-form',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})

export class RegistrationFormComponent implements OnInit {

MEAN STACK TECHNOLOGIES MODULE-2 57 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

registerForm!: FormGroup; submitted!:boolean;

constructor(private formBuilder: FormBuilder) { } ngOnInit()


{
[Link] = [Link]({
firstName: ['',[Link]], lastName:
['', [Link]], address:
[Link]({
street: [],
zip: [],
city: [] }),
email: ['', [[Link], validateEmail]],
});
}}
function validateEmail(c: FormControl): any {
let EMAIL_REGEXP = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-
Z]{2,5})$/; return EMAIL_REGEXP.test([Link]) ? null : { emailInvalid: {
message: "Invalid Format!"
}
};
}
#[Link]
.container {
width: 400px;
margin: 0 auto;
} form { margin-
bottom: 20px;
}

.form-group {
margin-bottom: 20px;
} label { display: block; margin- bottom:

MEAN STACK TECHNOLOGIES MODULE-2 58 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

5px; } input { width:


100%; padding: 8px;
box- sizing: border-
box;
}
.alert { color: #721c24;
background-color: #f8d7da;
border: 1px solid #f5c6cb;
padding: 8px; margin-top:
5px; border- radius: 4px; }
.btn- primary { background-
color: #1d1d1d; color: #fff;
border: none; padding: 10px
40px; border-radius: 4px;
cursor: pointer; } .btn-
primary:hover {
background-color: #0056b3;
} [hidden] { display: none;
} h3 { margin-
bottom: 10px;
}
.ng-valid[required] { border-
left: 5px solid #42A948;
}
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './app- [Link]'; import {
AppComponent } from './[Link]';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import {

MEAN STACK TECHNOLOGIES MODULE-2 59 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

RegistrationFormComponent } from
'./registration-form/[Link]';
@NgModule({
declarations: [ AppComponent,
RegistrationFormComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]
})
export class AppModule { }
#To run the Application ng
serve

OUTPUT

MEAN STACK TECHNOLOGIES MODULE-2 60 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise - 8

8A) Create a custom validator for the email field in the course registration form.

#Create a new component ng generate

component course-registration #Create a new file

in src/app as [Link]

Program :

#[Link]
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export
function emailValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => { if
(![Link]) {
return null;
} const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA- Z]{2,}$/;
const isValid = [Link]([Link]); return isValid ? null : {
invalidEmail: true };
};
}
#[Link]

<form [formGroup]="registrationForm" class="form">


<div class="form-group">
<label for="email" class="label">Email:</label>
<input type="email" id="email" formControlName="email" class="input"
/>
<div*ngIf="[Link]('email')?.hasError('required')" class="error-
message"> Email is required.

</div>

<div *ngIf="[Link]('email')?.hasError('invalidEmail')"

MEAN STACK TECHNOLOGIES MODULE-2 61 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

class="errormessage">
Invalid email address.
</div>
</div>
<button type="submit" class="button">Submit</button>
</form>

#[Link]

form {
max-width: 400px; margin:
50px; padding: 20px; border:
1px solid #ccc; border-
radius: 5px;
}

.label { display: block;


margin-bottom: 8px;
}

.input { width: 100%;


padding: 8px;
marginbottom: 16px; box-
sizing:
border-box;
}

.error-message { color:
red; margin-top: 8px;
}

MEAN STACK TECHNOLOGIES MODULE-2 62 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

.button { background-color:
#4caf50; color: white; padding:
9px 40px; border: none;
borderradius: 4px; cursor: pointer;
margin-top: 10px;
}

.button:hover { background-color: #45a049;


}

#[Link]

import { Component } from '@angular/core'; import { FormBuilder, FormGroup,


Validators } from '@angular/forms'; import { emailValidator } from '../[Link]';

@Component({
selector: 'app-course-registration', templateUrl: './course-
[Link]', styleUrls:
['./[Link]']
}) export class
CourseRegistrationComponent {
registrationForm: FormGroup;

constructor(private fb: FormBuilder) { [Link]


= [Link]({
email: ['', [[Link], emailValidator()]],
});
}
}
#[Link]

<app-course-registration></app-course-registration>
#[Link]

import { NgModule } from '@angular/core'; import { BrowserModule } from

MEAN STACK TECHNOLOGIES MODULE-2 63 ROLLNO: 22MH1A05D1


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

'@angular/platform-browser'; import { FormsModule, ReactiveFormsModule


} from '@angular/forms';
import { AppRoutingModule } from './[Link]'; import {
AppComponent } from './[Link]'; import {
CourseRegistrationComponent } from
'./course-registration/[Link]';

@NgModule({
declarations: [
AppComponent,
CourseRegistrationCompone nt
],
imports: [ BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
}) export class AppModule
{}

Output :

MEAN STACK TECHNOLOGIES MODULE-2 64 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

8B) Create a Book Component which fetches book details like id, name and displays
them on the page in a list format. Store the book details in an array and fetch the data
using a custom
service.
#Create a new component ng
generate component book
Program :
#in that book folder, create [Link] file

export class Book {


id!: number; name!:
string;
}
#in that book folder, create another [Link] file import { Book } from
'./book';
export let BOOKS: Book[] = [
{ id: 1, name: 'New HTML Book' },
{ id: 2, name: 'Advanced CSS' },
{ id: 3, name: 'Modern JavaScript' },
{ id: 4, name: 'Advanced Ajax Programming' },
{ id: 5, name: 'jQuery Essentials' },
{ id: 6, name: '[Link] Mastery' },
{ id: 7, name: 'AngularJS 1.x Handbook' },
{ id: 8, name: 'ng-book 2.0' },
{ id: 9, name: '[Link] Guide' },
{ id: 10, name: 'Yeoman in Action' }
];

#in C:\Angular\projectname\src\app\book> ng generate service book

#[Link]

import { Injectable } from '@angular/core';


import { BOOKS } from './books-data';
@Injectable({ providedIn:
'root' }) export class
BookService {

MEAN STACK TECHNOLOGIES MODULE-2 65 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

getBooks() {
return BOOKS;
}
}
#[Link]

import { Component, OnInit } from '@angular/core'; import


{ Book } from './book'; import { BookService } from
'./[Link]';
@Component({
selector: 'app-book', templateUrl: './[Link]',
styleUrls: ['./[Link]']
}) export class BookComponent implements OnInit { books!:
Book[]; constructor(private bookService: BookService) {
} getBooks() { [Link] =
[Link]();
}
ngOnInit()
{
[Link]();
}
}
#[Link]

<h2>My Books</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of books">

MEAN STACK TECHNOLOGIES MODULE-2 66 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<td><span class="badge">{{[Link]}}</span></td>
<td>{{[Link]}}</td>
</tr>
</tbody>
</table>
#[Link]
h2 { color:
#333; }

table {
width: 20%; border- collapse:
collapse; margin- top: 20px;
}

th, td { border: 1px solid


#ddd; padding: 8px;
text-align:

center;
}
th { background-color:
#f2f2f2; }
.badge { display: inline-block;
padding: 0.5em 0.7em; font-
size: 75%; font-weight: bold;
line-height:
1; color: #fff; text-align:
center; white-space: nowrap;
verticalalign: baseline;
border-radius: 0.25em;
background-color: #1d1d1d;
}
#[Link]

MEAN STACK TECHNOLOGIES MODULE-2 67 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<app-book></app-book>

Output :

8C) Create and use an observable in Angular.

Program :

#[Link]

<b> Using Observables!</b>


<h6 style="margin-bottom: 0">VALUES:</h6>
<div *ngFor="let value of myArray">{{ value }}</div>
<div style="margin-bottom: 0">ERRORS: {{ errors }}</div> <div style="margin-
bottom: 0">FINISHED: {{ finished }}</div>
<button style="margin-top: 2rem" (click)="fetchData()">Fetch Data</button>

#[Link]

import { Component } from '@angular/core'; import {


Observable } from 'rxjs';
@Component({
selector: 'app-root', styleUrls:
['./[Link]'], templateUrl:
'./[Link]'
}) export class AppComponent {

MEAN STACK TECHNOLOGIES MODULE-2 68 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

data!: Observable<number>;
myArray: number[] = []; errors!:
boolean; finished!: boolean;
fetchData(): void {
[Link] = new Observable(observer => {
setTimeout(() => { [Link](11); }, 1000), setTimeout(() => {
[Link](22); }, 2000), setTimeout(() => { [Link]();
}, 3000); }); [Link]((value) => [Link](value),

error => [Link] = true, ()


=> [Link] = true);
}
}
Output:

MEAN STACK TECHNOLOGIES MODULE-2 69 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

EXERCISE-9:
9A)Create an application for Server Communication using HttpClient
PROGRAM:
[Link]:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [BrowserModule, HttpClientModule],
}) export class AppModule
{ } [Link]:
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse,
HttpHeaders } from '@angular/common/http'; import { Observable, throwError } from
'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { Book } from './book';
@Injectable({
providedIn:'root'
}) export class BookService { constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> { return
[Link]<Book[]>('[Link] tap((data:
any) => [Link]('Data Fetched:' + [Link](data))),
catchError([Link]));
} } [Link]: import { Injectable
} from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { catchError, tap } from 'rxjs/operators'; import {
Observable, throwError } from 'rxjs'; import {
HttpErrorResponse } from '@angular/common/http'; import {
Book } from './book';
@Injectable({
providedIn: 'root'
})
export class BookService {
private handleError(err: HttpErrorResponse): Observable<any>
{ let errMsg = ''; if ([Link] instanceof
Error) {

MEAN STACK TECHNOLOGIES MODULE-2 70 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

// A client-side or network error occurred. Handle it accordingly.


[Link]('An error occurred:', [Link]);
errMsg = [Link];
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
[Link](`Backend returned code ${[Link]}`); errMsg
= [Link];
}
return throwError(()=>errMsg);
} } [Link] : export class
BookComponent implements OnInit { books!:
Book[]; errorMessage!: string; constructor(private
bookService: BookService) { } getBooks() {
[Link]().subscribe({
next: books => [Link] = books, error:error
=> [Link] =
<any>error
})
} ngOnInit() {
[Link]();
}
}
[Link]:
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{[Link]}}</span> {{[Link]}}
</li>
</ul>

MEAN STACK TECHNOLOGIES MODULE-2 71 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>


Output:

MEAN STACK TECHNOLOGIES MODULE-2 72 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

9B) Create a custom service called ProductService in which Http class is used to fetch
data stored in the JSON files.
PROGRAM:
[Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './[Link]'; import
{ AppComponent } from './[Link]';
import {HttpClientModule} from '@angular/common/http';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule

],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
[Link]
import { Component,OnInit } from '@angular/core';
import { UserService } from './[Link]';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
title:String = 'Http Services in Angular'; users:any;
constructor(private userService:UserService){

}
ngOnInit(){
[Link]().subscribe((data)=>{
[Link]=data
})
}
}
[Link]
import { Injectable } from '@angular/core';

MEAN STACK TECHNOLOGIES MODULE-2 73 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

@Injectable({
providedIn: 'root'
})
export class UserService { constructor(private

http:HttpClient) {

}
getAllUsers(){
return [Link]("[Link]
}
}
[Link]
<html>
<head>
<style>
/* [Link] */

table {
width: 100%;
border-collapse: collapse;
margin-top: 20px; /* Add some top margin for better spacing */
}

th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

th {
background-color: #f2f2f2;
}

tr:hover {
background-color: #f5f5f5;
}

</style>
</head>
<body>
<table border="2">
<tr>
<th>id</th>

import { HttpClient } from '@angular/common/http';

MEAN STACK TECHNOLOGIES MODULE-2 74 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<th>name</th>
<th>username</th>
<th>email</th>
</tr>
<tr *ngFor="let user of users">
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
</tr>
</table>
</body>
</html>
Output:

MEAN STACK TECHNOLOGIES MODULE-2 75 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

EXERCISE-10
10A) Create multiple components and add routing to provide navigation between
them.
[Link]:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; import {
Book } from '../book/book';
import { BookService } from '../book/[Link]';
@Component({
selector: 'app-dashboard', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class DashboardComponent implements
OnInit { books: Book[] = []; constructor( private
router: Router,
private bookService: BookService) { }
ngOnInit(): void { [Link]()
.subscribe({next:books => [Link] = [Link](1, 5)});
}
gotoDetail(book: Book): void { [Link](['/detail',
[Link]]);
}
}
[Link].htm1:
<h3>Top Books</h3>
<div class="grid grid-pad">
<div *ngFor="let book of books" (click)="gotoDetail(book)" class="col-1-4">
<div class="module book">
<h4>{{ [Link] }}</h4>
</div>
</div> </div>
[Link]:
[class*="col-"] {
float: left;
}

MEAN STACK TECHNOLOGIES MODULE-2 76 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

*,
*:after,
*:before {
-webkit-box-sizing: border-
box; -moz-box-sizing: border-
box; box-sizing: border-box; }
h3 { text-align: center; margin-
bottom: 0; } [class*="col-"] {
padding- right: 20px; padding-
bottom:
20px; }
[class*="col-"]:last-of-type
{ padding-right: 0; } .grid
{ margin: 0; } .col-1-4 {
width: 25%; } .module {
padding: 20px; text-align:
center; color: #eee; max-
height: 120px; min-width:
120px; background-color:
#607d8b; border-radius:
2px; } h4 { position:
relative; }
.module:hover {
background-color:
#eee; cursor: pointer;
color: #607d8b; } .grid-
pad { padding: 10px 0;
}
.grid-pad > [class*="col-"]:last-of-type { padding-

MEAN STACK TECHNOLOGIES MODULE-2 77 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

right: 20px;

}
@media (max-width: 600px)
{ .module { font-size:
10px; max-height: 75px;
}
}
@media (max-width: 1024px) {
.grid {
margin: 0;
}
.module { min-
width: 60px;
}
}
book-detail :
D:\MyApp>ng generate component bookDetail [Link] : import {
Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders,
HttpResponse } from '@angular/common/http'; import { Observable, throwError
} from 'rxjs';
import { catchError, tap, map} from 'rxjs/operators'; import { Book } from
'./book'; @Injectable({ providedIn:'root' }) export class BookService { booksUrl
= '[Link] private txtUrl =
'./assets/[Link]'; constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> { return [Link]<any>([Link],
{observe:'response'}).pipe( tap((data: any) => [Link]('Data
Fetched:' + [Link](data))),
catchError([Link]));
}

MEAN STACK TECHNOLOGIES MODULE-2 78 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

getBook(id: any) { return


[Link]().pipe( map((books) =>
[Link]((book) =>
[Link] == id))
);
}

addBook(book: Book): Observable<any> {


const options = new HttpHeaders({ 'Content-
Type': 'application/json' });
return
[Link]('[Link] book, {
headers: options }).pipe(
catchError([Link]));
}
updateBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content- Type':
'application/json' });
return
[Link]<any>('[Link] ate'
, book, { headers: options }).pipe( tap((_:
any) => [Link](`updated hero
id=${[Link]}`)), catchError([Link])
);

}
deleteBook(bookId: number):
Observable<any> { const url =
`${[Link]}/${bookId}`; return
[Link](url).pipe(
catchError([Link]));
}
private handleError(err: HttpErrorResponse):

MEAN STACK TECHNOLOGIES MODULE-2 79 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Observable<any> {
let errMsg = ''; if ([Link] instanceof Error)
{ // A client-side or network error occurred.
Handle it accordingly.
[Link]('An error occurred:',
[Link]); errMsg =
[Link];
} else {
// The backend returned an unsuccessful response
code.
// The response body may contain clues as to
what went wrong,
[Link](`Backend returned code
${[Link]}`); errMsg
= [Link];
}
return throwError(()=>errMsg);
} } book-
[Link]:
import { Component, OnInit } from
'@angular/core';

import { ActivatedRoute } from


'@angular/router'; import { Book
} from '../book/book';
import { BookService } from
'../book/[Link]';
@Component({
selector: 'app-book-detail', templateUrl:
'./[Link]', styleUrls:
['./[Link]'],
})
export class BookDetailComponent implements
OnInit { book!: Book; error!: any; constructor(
private bookService: BookService,
private route: ActivatedRoute

MEAN STACK TECHNOLOGIES MODULE-2 80 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

){}
ngOnInit() {
[Link]
[Link](params
=>
{

[Link]([Link]('id')).s
ubs cribe((book) => { [Link] = book

?? [Link];
});
});
}
goBack() {
[Link]();
} } book-
[Link] : <div
*ngIf="book">
<h2>{{ [Link] }} details!</h2>
<div><label>id: </label>{{ [Link] }}</div>
<div>
<label>name: </label> <input
[(ngModel)]="[Link]" placeholder="name"
/>
</div>
<button (click)="goBack()">Back</button>
</div> book-
[Link]:
label { display:
inline-block; width:
3em; margin:
0.5em 0; color:

#607d8b; font-
weight: bold;
} input { height:
2em; font-size:
1em; padding-left:
0.4em;
} button { margin-top:
20px; font-family: Arial;
background-color: #eee;
border: none; padding:
5px 10px; border-radius:

MEAN STACK TECHNOLOGIES MODULE-2 81 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

4px; cursor: pointer;


cursor: hand; }
button:hover {
background-color:
#cfd8dc;
}
button:disabled {
background-color: #eee;
color: #ccc; cursor: auto; }
page-not-
[Link]: <div>
<h1>404 Error</h1>
<h1>Page Not Found</h1>
</div> [Link]: import {
NgModule } from '@angular/core';
import { RouterModule, Routes } from
'@angular/router';
import { BookComponent } from
'./book/[Link]';
import { DashboardComponent } from
'./dashboard/[Link]'; import
{ BookDetailComponent } from
'./bookdetail/[Link]'; import {
PageNotFoundComponent } from
'./page-not-found/[Link]'; const
appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full'
},
{ path: 'books', component: BookComponent
},
{ path: 'detail/:id', component:
BookDetailComponent },
{ path: '**', component:
PageNotFoundComponent },
];
@NgModule({
imports: [
[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }

MEAN STACK TECHNOLOGIES MODULE-2 82 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

[Link] :
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform-browser';
import { HttpClientModule } from
'@angular/common/http';
import { FormsModule } from
'@angular/forms';
import { AppComponent } from
'./[Link]';
import { BookComponent } from
'./book/[Link]';
import { DashboardComponent } from
'./dashboard/[Link]'; import
{ BookDetailComponent } from
'./bookdetail/[Link]'; import
{ AppRoutingModule } from
'./[Link]';
import { PageNotFoundComponent } from
'./page-not-found/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule,
FormsModule, AppRoutingModule], declarations:
[AppComponent, BookComponent,
DashboardComponent,
BookDetailComponent,
PageNotFoundComponent],
providers: [], bootstrap:
[AppComponent]
}) export class AppModule { }
[Link]: import { Component } from
'@angular/core';
@Component({
selector: 'app-root', styleUrls:
['./[Link]'], templateUrl:
'./[Link]'

@NgModule({
imports: [
[Link](appRoutes)
],
exports: [
RouterModule
]
})

MEAN STACK TECHNOLOGIES MODULE-2 83 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

export class AppRoutingModule { }


[Link] :
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform-browser';
import { HttpClientModule } from
'@angular/common/http';
import { FormsModule } from
'@angular/forms';
import { AppComponent } from
'./[Link]';
import { BookComponent } from
'./book/[Link]';
import { DashboardComponent } from
'./dashboard/[Link]'; import
{ BookDetailComponent } from
'./bookdetail/[Link]'; import
{ AppRoutingModule } from
'./[Link]';
import { PageNotFoundComponent } from
'./page-not-found/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule,
FormsModule, AppRoutingModule], declarations:
[AppComponent, BookComponent,
DashboardComponent,
BookDetailComponent,
PageNotFoundComponent],
providers: [], bootstrap:
[AppComponent]
}) export class AppModule { }
[Link]: import { Component } from
'@angular/core';
@Component({
selector: 'app-root', styleUrls:
['./[Link]'], templateUrl:
'./[Link]'

}) export class
AppComponent { title =
'Tour of Books';
}
[Link]:
<h1>{{title}}</h1>
<nav>

MEAN STACK TECHNOLOGIES MODULE-2 84 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<a [routerLink]='["/dashboard"]' routerLinkActive="active">Dashboard</a>


<a [routerLink]='["/books"]'
routerLinkActive="active">Books</a>
</nav>
<router-outlet></router- outlet>
[Link] :
/* Master Styles */ h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif; font- size:
250%;
} h2, h3 { color: #444; font-family:
Arial, Helvetica, sans-serif; font-
weight: lighter; } body{ margin: 2em;
} body, input[text], button { color:
#888; font-family: Cambria, Georgia;
} a { cursor: pointer;
cursor: hand; } button {
font-family: Arial;
background-color: #eee;
border: none; padding: 5px
10px; border-radius: 4px;
cursor: pointer; cursor:
hand; } button:hover {
background-color: #cfd8dc;
} button:disabled {
background-color:
#eee; color: #aaa; cursor:
auto;
}
/* Navigation link styles */ nav
a { padding: 5px 10px; text-
decoration: none; margin-right:
10px; margin- top: 10px;
display: inline- block;
background-color: #eee;
border-radius: 4px; } nav
a:visited, a:link { color:
#607D8B; } nav a:hover {

color: #039be5;
background-color:
#CFD8DC; } nav [Link] {
color: #039be5; }
/* everywhere else */
*{
font-family: Arial, Helvetica, sans-serif;

MEAN STACK TECHNOLOGIES MODULE-2 85 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

} [Link]:
/* You can add global styles to this file, and
also import other style files */
body{
padding:10px; }
[Link]
:
import { Component, OnInit } from
'@angular/core'; import { Book } from './book';
import { BookService } from './[Link]';
@Component({
selector: 'app-book', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class BookComponent implements
OnInit {
books!: Book[];
errorMessage!: string;
constructor(private bookService:
BookService) { } getBooks() {
[Link]().subscribe({
next: books => [Link] = books, error:error
=> [Link] =
<any>error
})
}

ngOnInit(): void {
[Link]();
}
}
[Link]:
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{ [Link] }}</span>
{{ [Link] }}
</li>
</ul>

MEAN STACK TECHNOLOGIES MODULE-2 86 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

MEAN STACK TECHNOLOGIES MODULE-2 87 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

10B) Consider the same example used for routing. Add route guard to
BooksComponent. Only after logging in, the user should be able to access
BooksComponent. If the user tries to give the URL of Bookscomponent in another tab
or window, or if the user tries to reload the BooksComponent page, it should be
redirected to LoginComponent.

Program:
[Link]

<h3 style="position: relative; left: 60px">Login Form</h3>


<div *ngIf="invalidCredentialMsg" style="color: red">
{{ invalidCredentialMsg }}
</div>
<br />
<div style="position: relative; left: 20px">
<form [formGroup]="loginForm" (ngSubmit)="onFormSubmit()">
<p>User Name <input formControlName="username" /></p>
<p>
Password <input
type="password"
formControlName="password"
style="position: relative; left: 10px"
/>
</p>
<p><button type="submit">Submit</button></p>
</form> </div> [Link]:
import { Component } from
'@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms'; import
{ Router } from '@angular/router';
import { LoginService } from './[Link]'; @Component({
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class LoginComponent {
invalidCredentialMsg!: string;
loginForm!: FormGroup;
constructor(
private loginService: LoginService, private
router: Router,
private formbuilder: FormBuilder
){
[Link] = [Link]({
username: [],

MEAN STACK TECHNOLOGIES MODULE-2 88 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

password: [],
});

}
onFormSubmit(): void { const uname =
[Link]; const pwd
= [Link];
[Link]
.isUserAuthenticated(uname, pwd)
.subscribe({next:(authenticated) => { if
(authenticated) {
[Link](['/books']);
} else {
[Link] = 'Invalid Credentials. Try again.';
}
}});
} } [Link]:
export class User
{
constructor(public userId: number, public username: string, public password: string) {
}
} [Link] : import { Injectable }
from '@angular/core'; import {
Observable, of } from 'rxjs'; import { map
} from 'rxjs/operators';
import { User } from './user';
const USERS = [
new User(1, 'user1', 'user1'),
new User(2, 'user2', 'user2')
];
const usersObservable = of(USERS); @Injectable({
providedIn: 'root'
})
export class LoginService { private
isloggedIn = false; getAllUsers():
Observable<User[]> {
return usersObservable;
}
isUserAuthenticated(username: string, password: string):
Observable<boolean> { return [Link]().pipe( map(users
=> {
const Authenticateduser = [Link](user => ([Link] === username)
&&
([Link] === password));
if (Authenticateduser)
{ [Link] = true;
} else {
[Link] = false;

MEAN STACK TECHNOLOGIES MODULE-2 89 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

}
return [Link];

);
}
isUserLoggedIn(): boolean {
return [Link];
}
} [Link]: import { Injectable } from
'@angular/core'; import { CanActivate, Router }
from '@angular/router'; import { LoginService }
from './[Link]';
@Injectable({
providedIn: 'root'
})
export class LoginGuardService implements CanActivate { constructor(private
loginService: LoginService, private router: Router) { }
canActivate(): boolean {
if ([Link]()) { return
true;
}
[Link](['/login']); return
false;
}
} [Link]:
import { NgModule } from '@angular/core'; import { BrowserModule } from
'@angular/platform-browser'; import { HttpClientModule } from
'@angular/common/http'; import { FormsModule, ReactiveFormsModule }
from '@angular/forms'; import { AppComponent } from './[Link]';
import { BookComponent } from './book/[Link]'; import {
DashboardComponent } from './dashboard/[Link]'; import {
BookDetailComponent } from './book-detail/[Link]'; import {
AppRoutingModule
} from './[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not-
[Link]'; import { LoginComponent } from './login/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule,
AppRoutingModule],
declarations: [AppComponent, LoginComponent, BookComponent,
DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
}) export class AppModule { } [Link]: import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router'; import
{ BookComponent } from './book/[Link]'; import { DashboardComponent

MEAN STACK TECHNOLOGIES MODULE-2 90 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

} from './dashboard/[Link]'; import { BookDetailComponent } from


'./book-detail/[Link]'; import { PageNotFoundComponent } from
'./page-not-found/[Link]';

import { LoginGuardService } from './login/login-


[Link]'; import { LoginComponent } from
'./login/[Link]'; const appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'books', component: BookComponent , canActivate:[LoginGuardService] },
{ path: 'detail/:id', component: BookDetailComponent },
{path: 'login',component:LoginComponent},
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({
imports: [
[Link](appRoutes)
],
exports: [
RouterModule
]
}) export class
AppRoutingModule { } Output:

MEAN STACK TECHNOLOGIES MODULE-2 91 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

10C) Asynchronous Routing Apply lazy loading to BookComponent. If lazy loading is


not added to the demo, it has loaded in 1.14 s. Observe the load time at the bottom of the
browser console. Press F12 in the browser and click the Network tab and check the
Load time

Program: [Link]:
import { NgModule } from '@angular/core'; import {
RouterModule, Routes } from '@angular/router'; import {
BookComponent } from './[Link]'; import {
LoginGuardService } from '../login/[Link]'; const
bookRoutes: Routes = [
{
path: '',
component: BookComponent,
canActivate: [LoginGuardService]
}
];
@NgModule({
imports: [[Link](bookRoutes)],
exports: [RouterModule]
}) export class BookRoutingModule { }
[Link] : import { NgModule } from
'@angular/core'; import { CommonModule } from
'@angular/common'; import { BookComponent } from
'./[Link]';
import { BookRoutingModule } from './[Link]';
@NgModule({
imports: [CommonModule, BookRoutingModule],
declarations: [BookComponent]
})
export class BookModule { } app- [Link]
:
import { NgModule } from '@angular/core'; import {
RouterModule, Routes } from '@angular/router';
import { BookDetailComponent } from './book-detail/[Link]'; import {
BookComponent } from './book/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ LoginGuardService } from './login/[Link]';
import { LoginComponent } from './login/[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not- [Link]';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'books', loadChildren: () => import('./book/[Link]').then(m =>
[Link]) },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent } ,

MEAN STACK TECHNOLOGIES MODULE-2 92 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

{ path: '**', component: PageNotFoundComponent }

];
@NgModule({
imports: [
[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }

[Link]:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http'; import
{ FormsModule, ReactiveFormsModule } from
'@angular/forms'; import { AppComponent } from
'./[Link]';
import { BookComponent } from './book/[Link]'; import {
DashboardComponent } from './dashboard/[Link]'; import {
BookDetailComponent } from './book- detail/[Link]'; import {
AppRoutingModule } from './[Link]';
import { PageNotFoundComponent } from './page-not-found/page- [Link]';
import { LoginComponent } from './login/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule,
AppRoutingModule],
declarations: [AppComponent, LoginComponent,
DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
providers: [], bootstrap: [AppComponent]
})
export class AppModule { }

MEAN STACK TECHNOLOGIES MODULE-2 93 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Output:
If lazy loading is not added to the demo, it has loaded in 1.14 s. Observe the load time at the
bottom of the browser console. Press F12 in the browser and click the Network tab and check
the Load time

If lazy loading is added to the demo, it has loaded in 900 ms. As BookComponent will be
loaded after login, the load time is reduced initially.

MEAN STACK TECHNOLOGIES MODULE-2 94 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

10D) Implement Child Routes to a submodule.

Program:

[Link]:

import { NgModule } from '@angular/core'; import { RouterModule, Routes }

from '@angular/router'; import { BookComponent } from './[Link]';

import { LoginGuardService } from '../login/login- [Link]'; import {

DashboardComponent } from '../dashboard/[Link]'; import {

BookDetailComponent } from '../book-detail/[Link]'; const

bookRoutes: Routes = [

path: '',

component: BookComponent,

children: [

{ path: 'dashboard', component: DashboardComponent },

{ path: 'detail/:id', component: BookDetailComponent }

],

canActivate: [LoginGuardService]

}];

@NgModule({

imports: [[Link](bookRoutes)],

exports: [RouterModule]

}) export class BookRoutingModule

{ } [Link] :

MEAN STACK TECHNOLOGIES MODULE-2 95 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

import { NgModule } from '@angular/core'; import { BookComponent } from

'./[Link]'; import { BookRoutingModule } from './book-

[Link]'; import { FormsModule } from '@angular/forms'; import {

BookDetailComponent } from '../book-detail/book- [Link]'; import

{ DashboardComponent } from '../dashboard/[Link]'; import {

CommonModule } from '@angular/common';

@NgModule({ imports: [ CommonModule, BookRoutingModule,

FormsModule], declarations: [BookComponent, BookDetailComponent,

DashboardComponent]

}) export class BookModule

{ } [Link] :

<br/>

<h2>MyBooks</h2>

<ul class="books">

<li *ngFor="let book of books " (click)="gotoDetail(book)">

<span class="badge">{{[Link]}}</span> {{[Link]}}

</li></ul>
<div><router-outlet></router-outlet></div>
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>

[Link] :

<h1>{{title}}</h1>

<nav>

<a [routerLink]='["/books"]' routerLinkActive="active">Books</a>

<a [routerLink]='["/books/dashboard"]' routerLinkActive="active">Dashboard</a>

</nav>

MEAN STACK TECHNOLOGIES MODULE-2 96 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

<router-outlet></router-outlet> app-

[Link]:

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from

'@angular/router'; import { LoginComponent } from './login/[Link]'; import {

PageNotFoundComponent } from './page-not-found/page-not- [Link]'; const

appRoutes: Routes = [

{ path: '', redirectTo: '/login', pathMatch: 'full' },

{ path: 'login', component: LoginComponent },

{ path: 'books', loadChildren: () =>


import('./book/[Link]').then(m => [Link]) },

{ path: '**', component: PageNotFoundComponent }

];
export class AppRoutingModule { }

[Link]:

import { NgModule } from '@angular/core'; import {

BrowserModule } from '@angular/platform-browser'; import {

HttpClientModule } from '@angular/common/http'; import {

ReactiveFormsModule

} from '@angular/forms'; import { AppComponent } from

'./[Link]'; import { AppRoutingModule } from

'./[Link]'; import { LoginComponent } from

'./login/[Link]';

@NgModule({

imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,


AppRoutingModule], declarations: [AppComponent, LoginComponent],

MEAN STACK TECHNOLOGIES MODULE-2 97 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

providers: [], bootstrap:

[AppComponent]

}) export class AppModule

{ } [Link]:

gotoDetail(book: Book): void {

[Link](['/books/detail', [Link]]);

[Link]:

<h3>Top Books</h3>

<div class="grid grid-pad">

<div *ngFor="let book of books" (click)="gotoDetail(book)" class="col-1-4">

<div class="module book">


<h4>{{ [Link] }}</h4>

</div>

</div> </div>

[Link]:

import { Component, OnInit } from '@angular/core';

import { Router } from '@angular/router'; import {

Book } from '../book/book'; import { BookService }

from '../book/[Link]';

@Component({

selector: 'app-dashboard', templateUrl:

'./[Link]', styleUrls:

['./[Link]']

}) export class DashboardComponent implements

MEAN STACK TECHNOLOGIES MODULE-2 98 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

OnInit { books: Book[] = []; constructor( private

router: Router, private bookService:

BookService) { } ngOnInit(): void {

[Link]()

.subscribe(books => [Link] = [Link](1, 5));

[Link](['/books/detail', [Link]]); }

OUTPUT

MEAN STACK TECHNOLOGIES MODULE-2 99 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Exercise-11

11. a) Installing MongoDB on the local computer, Create MongoDB Atlas Cluster
INSTALLIING MONGODB:
1. Download MongoDB:

> Visit the MongoDB download center: MongoDB center


> Select the appropriate version for your operating system.
> Follow the installation instructions for your OS.
2. INSTALLATION:

> For windows , run the installer and follows the prompts.
Setting Up MongoDB Atlas:
1. create an Account: Go to the MongoDB website and create an account if you haven‟t
already: MongoDB Atlas
2. create a Cluster: > Once logged in, click on “‟Clusters” and then “Create a Cluster”. >
Choose your prefered cloud provider, cluster tier, and other settings. You can often start with
the free tier for testing purposes. > Follow the prompts to set up your cluster
3. whitelist IP Adress (if necessary): Under “Security” > “Network Access”, add your IP
address to the whitelist to allow access to the cluster.
4. Connect to Your Cluster: Once your cluster is set up, click on “Connect” and follow the
instructions to connect to your cluster using MongoDB Compass or via connection strings
for your application.
Writing Code to Interact with MongoDB:
1. INSTALL the „mongodb‟ Package:

npm install mongodb


2. Connect to MongoDB Atlas in your [Link] application:

const { MongoClient } = require('mongodb');


// Connection URI
const uri = 'your_connection_string_here';
// Create a new MongoClient
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true
}); async function run() {
try {
// Connect to the MongoDB cluster await
[Link]();

MEAN STACK TECHNOLOGIES MODULE-2 100 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

[Link]('Connected to MongoDB Atlas');


// ... (perform operations here)
} finally {
// Close the connection when done

await [Link]();
}
}
run().catch([Link]) ;

MEAN STACK TECHNOLOGIES MODULE-2 101 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

11b) Write MongoDB queries to perform CRUD operations on document using insert(),
find(), update(), remove()

Program:
const express=require('express') const
app=express() const
mongoose=require('mongoose') const
bodyparser=require('body-parser') const
fs = require('fs');
const https = require('https');
[Link]([Link]())
let b=[Link]('mongodb://[Link]:27017/cserocks')
const cses3 = new [Link]({
_id:{
type:Number,
required:true
},
name:{
type:String,
required:true
}
}, {
collection:"acoerocks",
versionKey:false
}
)
const post=[Link]("acoerocks",cses3)
[Link]('/ret',(req,res)=>{
[Link]().then((data)=>{[Link](data)})
})
[Link]('/',async
(req,res)=>{ var data={
_id:[Link]._id,
name:[Link]
}
const m=new post(data)
[Link]().then((info)=>{[Link](info)})
})
[Link]('/pin/:id',async (req,res)=>{
[Link]({_id:[Link]}).then((data)=>{
[Link](data)
}) })
[Link]('/update/:id',async (req,res)=>{
var data={

MEAN STACK TECHNOLOGIES MODULE-2 102 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

name:[Link]
}
var n=[Link]
[Link](n,data).then(()=>{
[Link]("UPDATED SUCEFULLLFUL")
})
})
[Link]('/delete/:id',async (req,res)=>{ var n=[Link]
[Link](n).then(()=>{
[Link]("deleted SUCEFULLLFUL")
})
})
var server=[Link](1000, function () {
[Link]('Server running on HTTP');
var n=[Link]
[Link](n,data).then(()=>{
[Link]("UPDATED SUCEFULLLFUL")
})
})

[Link]('/delete/:id',async (req,res)=>{

var n=[Link]
[Link](n).then(()=>{
[Link]("deleted SUCEFULLLFUL")
})
})
var server=[Link](1000, function () {
[Link]('Server running on HTTP');
});
Output:
Get: [Link]

MEAN STACK TECHNOLOGIES MODULE-2 103 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

MEAN STACK TECHNOLOGIES MODULE-2 104 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

Put: [Link]

Delete: [Link]

MEAN STACK TECHNOLOGIES MODULE-2 105 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

EXPERIMENT-12:
12a) Write MongoDB queries to Create and drop databases and collections.
Program:

The “use” Command for Creating Database in MongoDB:


Syntax:
Use my_project _db
Example:

Here 'use' is the command for creating a new database in MongoDB and 'my_project_db' is
the name of the database. This will prompt you with a message that it has switched to a new
DB (database) name 'my_project_db'.
View the List of Databases in MongoDB:
 Shows dbs

Example:

[Link]({“name”:”fruits:apples”})
Now, when you again use the show dbs command, it will now show your created database name in
the list.

Deleting a Database in MongoDB:


Example:
[Link](){

“dropped”: ”my_project_db”, “ok”: 1}

MEAN STACK TECHNOLOGIES MODULE-2 106 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

This will drop the existing database.

12b) Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(),
aggregate().
npm install mongodb
Program:
const { MongoClient } = require('mongodb');

// MongoDB connection string


const uri = 'mongodb://localhost:27017/myDatabase';

// Connect to MongoDB
[Link](uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(async (client) => {
[Link]('Connected to MongoDB');

const db = [Link]();

const collection = [Link]('myCollection');


find():
The „find()‟ method is used to querydocuments in a collection
// Assuming a collection named "users"
[Link]({ age: { $gte: 25 } });
This query will find all users with an age greater than or equal to 25. Limit():
The limit() method is used to limit the number of documents returned.

MEAN STACK TECHNOLOGIES MODULE-2 107 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

// Limiting the results to 5 documents [Link]().limit(5);


This querywill return only the first 5 documents from the "users" collection.
Sort():
The sort() method is used to sort the documents returned.
// Sorting documents by age in ascending order
[Link]().sort({ age: 1 });

This query will return documents sorted by age in ascending order. CreateIndex():
The createIndex() method is used to create indexes to improve query performance.
// Creating an index on the "name" field [Link]({
name: 1 });
This querywill create an index on the "name" field in the "users" collection. Aggregate():
The aggregate() method is used for data aggregation operations.
// Aggregating and counting users by age [Link]([
{ $group: { _id: "$age", count: { $sum: 1 } } },
{ $sort: { _id: 1 } }
]);
This query will count the number of users for each age and sort the results by age.
OUTPUT:
Assuming a sample "users" collection: [
{ "_id": 1, "name": "Alice", "age": 30 },
{ "_id": 2, "name": "Bob", "age": 25 },
{ "_id": 3, "name": "Charlie", "age": 30 },
{ "_id": 4, "name": "David", "age": 28 },
{ "_id": 5, "name": "Eve", "age": 25 }
]

• find({ age: { $gte: 25 } }) would output documents with an age of 25 or greater.


• find().limit(3) would output the first 3 documents in the collection.
• find().sort({ age: 1 }) would output documents sorted by age in ascending order.
• createIndex({ name: 1 }) would create an index on the "name" field.
• aggregate(...) would output something like:

MEAN STACK TECHNOLOGIES MODULE-2 108 ROLLNO: 22MH1A05D1


: ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY(A:)

[
{ "_id": 25, "count": 2 },
{ "_id": 28, "count": 1 },

MEAN STACK TECHNOLOGIES MODULE-2 109 ROLLNO: 22MH1A05D1

You might also like