MST Lab Manual (R20)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


(DATA SCIENCE)

MEANStackTechnologiesLaboratory(20CS6S06)
IVB.Tech I Sem
(R20 Regulation)

LAB MANUAL
Prepared by

M V Rajesh
Associate Professor
Pragati Engineering College
(Autonomous)
(Approved by AICTE, New Delhi & Affiliated to JNT University, Kakinada)
1-378, ADB Road, Surampalem – 533 437

Department of CSE(DS), PEC


MEANStackTechnologiesLab Manual

INDEX

Exercise Program Name Page


Number Number
a) Course Name: Node.js Module Name: How to use Node.js
Verify how to execute different functions successfully in the
Node.js platform.
1
b) Course Name: Node.js Module Name: Create a web server in
Node.js Write a program to show the workflow of JavaScript
code executable by creating web server in Node.js
a) Course Name: Node.js Module Name: Modular
programming in Node.js Write a Node.js module to show the
workflow of Modularization of Node application
b) b) Course Name: Node.js Module Name: Restarting Node
2 Application Write a program to show the workflow of
restarting a Node application.
c) Course Name: Node.js Module Name: File Operations
Create a text file src.txt and add the following data to it.
Mongo, Express, Angular, Node.
a) Course Name: Express.js Module Name: Defining a route,
Handling Routes, Route Parameters, Query Parameters
Implement routing for the Adventure Trails application by
embedding the necessary code in the routes/route.js file.
b) Course Name: Express.js Module Name: How Middleware
works, Chaining of Middle wares, Types of Middle wares In
my Notes application: (i) we want to handle POST
3 submissions. (ii) display customized error messages. (iii)
perform logging
c) c) Course Name: Express.js Module Name: Connecting to
MongoDB with Mongoose, Validation Types and Defaults
Write a Mongoose schema to connect with MongoDB.
d) d) Course Name: Express.js Module Name: Models Write a
program to wrap the Schema into a Model object.

 Course Name: Express.js Module Name: CRUD


Operations Write a program to perform various CRUD
(Create-Read-Update-Delete) operations using Mongoose
library functions
 Course Name: Express.js Module Name: API
4
Development In the myNotes application, include APIs
based on the requirements provided. (i) API should fetch
the details of the notes based on a notesID which is
provided in the URL. Test URL -
http://localhost:3000/notes/7555 (ii) API should update

1
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

the details bas


 Course Name: Express.js Module Name: Why Session
management, Cookies Write a program to explain session
management using cookies.
 Course Name: Express.js Module Name: Sessions Write
a program to explain session management using sessions.
 Course Name: Express.js Module Name: Why and What
Security, Helmet Middleware Implement security
features in myNotes application
https://infyspringboard.onwingspan.com/web/en/viewer/

 Course Name: Typescript Module Name: Basics of


TypeScript On the page, display the price of the mobile-
based in three different colors. Instead of using the
number in our code, represent them by string values like
GoldPlatinum, PinkGold, SilverTitanium.
 Course Name: Typescript Module Name: Function
Define an arrow function inside the event handler to filter
the product array with the selected product object using
the productId received by the function. Pass the selected
product object to the next screen.
 Course Name: Typescript Module Name: Parameter
Types and Return Types Consider that developer needs to
declare a function - getMobileByVendor which accepts
5 string as input parameter and returns the list of mobiles.
 Course Name: Typescript Module Name: Arrow Function
Consider that developer needs to declare a manufacturer's
array holding 4 objects with id and price as a parameter
and needs to implement an arrow function - myfunction
to populate the id parameter of manufacturers array
whose price is greater than or equ
 Course Name: Typescript Module Name: Optional and
Default Parameters Declare a function -
getMobileByManufacturer with two parameters namely
manufacturer and id, where manufacturer value should
passed as Samsung and id parameter should be optional
while invoking the function, if id is passed as 101 then
this function shoul
 Course Name: Typescript Module Name: Rest Parameter
Implement business logic for adding multiple Product
values into a cart variable which is type of string array
 Course Name: Typescript Module Name: Creating an
Interface Declare an interface named - Product with two
properties like productId and productName with a
number and string datatype and need to implement logic
6 to populate the Product details.
 Course Name: Typescript Module Name: Duck Typing
Declare an interface named - Product with two properties
like productId and productName with the
number and string datatype and need to implement logic
to populate the Product details.

2
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

a) Course Name: MongoDB Essentials - A Complete


MongoDB Guide Module Name: Installing MongoDB on
the local computer, Create MongoDB Atlas Cluster Install
MongoDB and configure ATLAS
7 b) Course Name: MongoDB Essentials - A Complete
MongoDB Guide Module Name: Introduction to the CRUD
Operations Write MongoDB queries to perform CRUD
operations on document using insert(), find(), update(),
remove()
a) Course Name: MongoDB Essentials - A Complete
MongoDB Guide Module Name: Create and Delete
Databases and Collections Write MongoDB queries to Create
and drop databases and collections
8 b) b) Course Name: MongoDB Essentials - A Complete
MongoDB Guide Module Name: Introduction to MongoDB
Queries Write MongoDB queries to work with records using
find(), limit(), sort(), createIndex(), aggregate()

a) Course Name: Angular JS Module Name: Angular


Application Setup Observe the link
http://localhost:4200/welcome on which the mCart
application is running. Perform the below activities to
understand the features of the application.
b) Course Name: Angular JS Module Name: Components and
9 Modules Create a new component called hello and render
Hello Angular on the page
c) Course Name: Angular JS Module Name: Elements of
Template Add an event to the hello component template and
when it is clicked, it should change the course Name
d) Course Name: Angular JS Module Name: Change Detection
progressively building the Pool Carz application
a) Course Name: Angular JS Module Name: Structural
Directives - ngIf Create a login form with username and
password fields. If the user enters the correct credentials, it
should render a "Welcome <>" message otherwise it should
render "Invalid Login!!! Please try again..." message
b) Course Name: Angular JS Module Name: ngFor Create a
courses array and rendering it in the template using ngFor
10 directive in a list format
c) c) Course Name: Angular JS Module Name: ng Switch
Display the correct option based on the value passed to ng
Switch directive.
d) d) Course Name: Angular JS Module Name: Custom
Structural Directive Create a custom structural directive
called 'repeat' which should repeat the element given a
number of times.

3
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-1:
ProblemStatement1:
VerifyhowtoexecutedifferentfunctionssuccessfullyintheNode.jsplatform.
Todo:
Step1:Createafiledemo.jsinthefolder created earlier.
Step2:Addthefollowinglinesofcodeinthecreated file.

functiontester(){
alert("Hello! Iamanalertbox!");
}
tester();
Step3:Runthecodeandobservetheoutput.
Step4: Modifythecodeasshownbelow:

functiontester(){ var
message;
if(confirm("Pressabutton!"))
{
message="YoupressedOK!";
}
else
{
message="YoupressedCancel!";
}
console.log(message);
}
tester();

Step5:Runthecodeandobservetheoutput.
Observation
Functionsthatperform browserinteractionarenot compatiblewithNode.js.You can try out other
functionsas well and observe the output.

4
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:
WriteaprogramtoshowtheworkflowofJavaScriptcodeexecutablebycreatingwebserverin Node.js.

Highlights:
 Using require() and createServer()method
 RunningawebserverinNode.js
Demo steps:

Step1:CreateanewJavaScriptfilehttpserver.js andincludetheHTTPmodule
consthttp=require("http");

Step2:Use thecreateServer()methodoftheHTTPmoduletocreateawebserver.
var server=http.createServer((req,res)=>
{
res . write ("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");

Step3:Savethefileandstarttheserverusingthe node command.Whenthefileexecutes successfully, we


canobserve the following outputintheconsole.

Step4:Wewillobservethefollowinginthebrowser.

ThuswehavecreatedaNodeserverandsenttheresponsefromtheservertotheclient.

5
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-2:
ProblemStatement1:
WriteaNode.jsmoduleto showtheworkflowofModularization ofNodeapplication.
Highlights:
 Creatingamodule
 Loadingthemodule

Demosteps:

LetustryouthowtocreateandloadamoduleinaNodeapplication

Step1:CreateafileDBModule.jswithintheNodeJSfoldercreated earlier.

exports.authenticateUser=(username,password)=>{

if(username==="admin"&&password==="admin"){ return
"Valid User";
}elsereturn"InvalidUser";

};

Step2:Modifythefile httpserver.jsfilecreatedearlierasbelow.

app.js

consthttp=require("http");
vardbmodule= require("./DBModule");
var server = http.createServer((request, response) => {
result = dbmodule.authenticateUser("admin","admin");
response.writeHead(200,{"Content-Type":"text/html"});
response.end("<html><body><h1>"+result +"</h1></body></html>");
console.log("Request received");
});
server.listen(3000);
console.log("Serverisrunningatport3000");
Inthehttpserver.jsfile,weareloadingthemodule"DBModule"andtheninvokingthefunction named
"authenticateUser()".

Step3:Runthe httpserver.jsusingthenodecommand

6
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

OpenabrowserandnavigatetoURL "http://localhost:3000" andobservetheoutput

7
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:
WriteaprogramtoshowtheworkflowofrestartingaNodeapplication.

Wheneverwe are working on a Node.jsapplication and we do any change in code after the
applicationis started, wewill berequiredtorestarttheNodeprocessforchangestoreflect. Inorderto
restartthe server andto watchfor any code changesautomatically, we canuse the Nodemon tool.
Nodemon

Nodemonisacommand-lineutilitythatcanbeexecutedfromtheterminal.Itprovidesa differentway to start a


Node.js application. It watches the application and whenever any change is detected, it restarts the
application.

Itisveryeasytogetstartedwiththistool.Toinstallitintheapplication,runthebelowcommand.
npminstallnodemon-g

Once the 'nodemon' is installed in the machine, the Node.js server code canbe executed byreplacing
the command"node" with "nodemon".
nodemonapp.js

Thusthe 'nodemon' starts the applicationinwatchmode and restart the applicationwhenanychange is


detected.
Consider asimpleNode.jscodefor creatingawebserver. const
http = require("http");
var server = http.createServer((req, res) => {
res.write("HelloWorld!Ihavecreatedmy firstserver!");
res.end();
});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");

Observetheconsoleonstartingthenodemoninacommandpromptwindow.

8
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Nowopenthe applicationcodeand do changesinthecodeasbelow. const


http = require("http");
var server = http.createServer((req, res) => {
console.log("Request URL is " + req.url);
res.write("HelloWorld!Ihavecreatedmy firstserver!");
res.end();

});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");

Observe the console message inthe commandprompt.Nodemonautomaticallyrestartedtheserveron


observing changesin the code

Toavoidoverandoverrestartingofserverforsmallchangestoreflect.Itisimportant tohavean
automaticrestartoftheserver ofyour application. Use nodemon for this purpose.

9
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement3:
Createatextfilesrc.txtand addthefollowingdatato it.Mongo,Express,Angular,Node.
Creatingatextfile:
constfs=require('fs');
const{ promisify } = require('util');
constwriteFile=promisify(fs.writeFile);
(async () => {
try{
await writeFile('src.txt', `Mongo, Express,Angular,Node`);
console.log('Filecreatedsuccessfullywithpromisify and async/await!');
} catch (err) {
console.log(err);
}
})();

Output:
Readingatext file:
constfs=require('fs');
const{ promisify } = require('util');
constreadFile=promisify(fs.readFile);
(async () => {
try{
constfileData=awaitreadFile('src.txt','utf8');
console.log(fileData);
} catch (err) {
console.log(err);
}
})();
Output:

10
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-3:
ProblemStatement1:
Implementroutingforthe Adventure Trailsapplicationbyembedding thenecessarycodeinthe
routes/route.js file.
Step1:Setuptheproject
Createanewdirectoryfor your projectandnavigate intoit:
bash
mkdirAdventureTrailsApp
cd AdventureTrailsApp
Initializetheprojectandcreateapackage.jsonfile:
bash
npminit-y
Step2:InstallExpress
InstallExpressinyourproject:
bash
npminstallexpress
Step 3: Create the directory structure
Createthefollowingdirectorystructure:
- AdventureTrailsApp
- routes
-trailRoutes.js
- index.js
- package.json
Step 4:Createtheindex.jsfile
Inthe`index.js` file,setuptheExpress serverandincludethe necessaryroutes:
javascript
constexpress=require('express');
const app = express();
consttrailRoutes=require('./routes/trailRoutes');
// Middlewaretoparserequestbodies as JSON app.use(express.json());
//UsetheAdventureTrailsroutes
app.use('/api/trails',trailRoutes);
//Starttheserver
constport=process.env.PORT||3000;
app.listen(port, () => {
console.log(`AdventureTrailsserverisrunningonhttp://localhost:${port}`);
});
Step5:CreatethetrailRoutes.jsfile
Inthe`routes/trailRoutes.js`file,definethe routesfortheAdventureTrailsapplication:
javascript

11
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

constexpress=require('express');
const router = express.Router();
//Sampledatafor trails(replacethiswithyouractual datasourceordatabase) const
trails = [
{id:1,name:'AdventureTrail1',length:'10km'},
{id:2,name:'AdventureTrail2',length:'8km'},
{id:3,name:'AdventureTrail3',length:'15km'},

];
// Route to get all trails
router.get('/', (req,res)=>{
res.json(trails);
});
// Route to get a specific trail byID
router.get('/:id', (req, res) => {
consttrailId=parseInt(req.params.id);
const trail =trails.find((trail) =>trail.id===trailId); if
(trail) {
res.json(trail);
}else{

res.status(404).json({message:'Trailnotfound'});
}
});

//Addmoreroutesasperyour application'srequirements
module.exports= router;
Step6:Runtheapplication

Starttheapplicationbyrunningthe `index.js`file: bash


node index.js
Now, your AdventureTrails application is up and running! It will be accessible at
`http://localhost:3000/api/trails`. Youcantest the routes usingtools like Postmanor bymakingHTTP
requests inyourpreferred programminglanguage.

12
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:
InmyNotesapplication:(i)wewanttohandlePOSTsubmissions.(ii)displaycustomizederror messages.
(iii) performlogging.
Handling post submissions in the myNotes application involves processing user input, validating it,
displaying customized error messages for any issues, and performing logging to keep track of
importantevents. Below,I'll outline the steps you cantake to achieve these functionalities:
1. *FormSubmissionandValidation*:

- CreateanHTMLformwithappropriateinputfields(e.g.,title,content)andasubmitbutton.

- Inthebackend,whentheformissubmitted,extractthedatafromtherequest.
- Validate the data to ensure it meets the required criteria (e.g., checkingifthe title and contentare
not empty and within character limits).

2. *DisplayCustomizedErrorMessages*:

- Ifanyvalidationfails,generatespecificerrormessagesfortheuser.

- Displaytheseerrormessagesontheform,sotheuserknowswhatneedstobecorrected.

- You can use server-side rendering or AJAX to handle formsubmissions and show errors without
refreshing the entire page.
3. *Logging*:
- Implement alogging mechanism to record important events and errors that occur duringthe form
submission process.
- Choosean appropriatelogging library orwritecustom logging functionstohandledifferent log levels
(e.g., info, warning, error).
- Logrelevantinformationsuchastheuser,timestamp,errormessage,andanyotheradditional details that
mightbeusefulfor debuggingor monitoring.
Here'sasimpleexample of how you could handle post submissions, show custom error messages, and
perform loggingin a Python-basedweb applicationusing Flask:

python

#Assumingyou have alreadysetup the Flaskappandimported requiredmodules import


logging

13
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

app=Flask(name)

#Configurelogging

logging.basicConfig(filename='mynotes.log',level=logging.INFO
@app.route('/submit', methods=['POST'])
defsubmit_post():

#Getdatafromtheformsubmission
title = request.form.get('title')
content=request.form.get('content')
# Validate the data
ifnottitleornotcontent:

error_message = "Title and content cannotbe empty."


logging.warning(f"Formvalidationfailed:{error_message}")
return render_template('form.html',error_message=error_message) if
len(title) > 100 or len(content)> 1000:
error_message="Titleshouldbelessthan100charactersandcontentshouldbelessthan1000 characters."
logging.warning(f"Formvalidationfailed:{error_message}")

returnrender_template('form.html',error_message=error_message)

#Ifdata isvalid,savethepostinthe databaseand redirecttothe successpage # (Add


yourdatabase handling code here)
logging.info(f"Postsubmittedsuccessfully:Title-{title}") return
redirect(url_for('success'))
@app.route('/success')
def success():
return"Postsubmittedsuccessfully!"
@app.route('/')
defshow_form():
returnrender_template('form.html')

In thisexample,when the user submits the form, the `submit_post()` function is called, which extracts
the data, validates it, and shows an error message or saves the post based on the validation results.The
logging statementsare usedtokeep trackof important events inthe application.

14
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement3:
WriteaMongooseschematoconnectwithMongoDB.
ToestablishaconnectiontotheMongoDBdatabase,weneedtocreateaconnectionobjectusing Mongoose.
This is done throughthe below code:
const mongoose= require('mongoose');
mongoose.connect('mongodb://localhost:27017/Database_Name');
InLine 1,weareimportingthe Mongooselibraryintoour application.
InLine2,theconnect()methodtakesMongoDBprotocolfollowedbythehostandthedatabase name
asaparameter.

Let usnowestablish aconnection tothe MongoDBdatabase IntellectNotes for storing detailsusing the
below code:
const mongoose= require('mongoose');
mongoose.connect('mongodb://localhost:27017/IntellectNotes',{
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify:false,
useUnifiedTopology:true,
})
Line2:HerewearespecifyingtheURIwherethedatawillbestored/retrieved.Thesecond parameter
{ useNewUrlParser: true, useCreateIndex: true, useFindAndModify:false,
useUnifiedTopology:true}
istosuppressthebelowwarningsthrownbyMongoDB.
Implementationofcode:
First,make sureyouhaveinstalledtherequireddependencies:mongooseandMongoDB. bash
npminstallmongoosemongodb
Now,createafile(e.g.,`db.js`)todefinetheMongooseschemaandconnecttotheMongoDB database:
javascript
constmongoose=require('mongoose');
//Replace'your-mongodb-uri' withtheactualconnection stringtoyour MongoDBdatabase
constmongoURI= 'mongodb://localhost:27017/your-database-name';

15
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//ConnecttotheMongoDBdatabase
mongoose.connect(mongoURI,{
useNewUrlParser: true,
useUnifiedTopology:true,
})
.then(()=>console.log('MongoDBconnected successfully'))
.catch((err)=>console.error('ErrorconnectingtoMongoDB:',err.message));
// Define the Mongoose schema
constSchema=mongoose.Schema;
constnoteSchema=newSchema({
title: {
type: String,
required:true,
},
content: {
type:String,
required:true,
},
createdAt: {
type:Date,
default:Date.now,
},
});
// Create the 'Note' model using the 'noteSchema'
constNote =mongoose.model('Note',noteSchema);
module.exports= Note;
Inthis example, we create a simple schema for a `Note` withfields `title`,`content`,and `createdAt`.
We also connect to the MongoDB database using Mongoose and define a model called `Note` based
on the `noteSchema`.
Remember toreplace `'your-mongodb-uri'`withyour actual MongoDBconnectionstring.Thisshould
point to your MongoDBinstance, either locallyor ona cloud service like MongoDB Atlas.
ProblemStatement4:
Writeaprogramtowrapaschemaintomodelobject.
Createafile(e.g.,`noteModel.js`)to definetheMongooseschemaandwrapitintoaModel:
javascript
constmongoose=require('mongoose');
//Replace'your-mongodb-uri' withtheactualconnection stringtoyour MongoDBdatabase
constmongoURI= 'mongodb://localhost:27017/your-database-name';

16
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//ConnecttotheMongoDBdatabase
mongoose.connect(mongoURI,{
useNewUrlParser: true,
useUnifiedTopology:true,
})

.then(()=>console.log('MongoDBconnected successfully'))
.catch((err)=>console.error('ErrorconnectingtoMongoDB:',err.message));

// Define the Mongoose schema


constSchema=mongoose.Schema;
constnoteSchema=newSchema({
title: {
type:String,

required:true,
},
content: {
type:String,
required:true,
},

createdAt: {
type:Date,
default:Date.now,

},
});
// Create the 'Note' model using the 'noteSchema'
constNote =mongoose.model('Note',noteSchema);
module.exports= Note;
Now, in your main application file (e.g., `app.js`), you can use the `Note`model byimportingitfrom the
`noteModel.js` file:
Javascript

17
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

const express=require('express');
constNote=require('./noteModel');//Import theNotemodel const
app = express();
//Yourapplicationroutesandothermiddlewarecanbedefinedhere
//Forexample:
app.get('/notes', async (req,res)=>{ try
{
//FetchallnotesfromtheMongoDBdatabaseusingtheNotemodel const
notes = await Note.find({});
//Respondwiththefetched notes
res.json(notes);
}catch (err){
// Handle errors, e.g., send an error response
res.status(500).json({error:'Errorfetchingnotes' });
}
});
// Start the server
constport=3000;

app.listen(port,()=>{
console.log(`Serverrunningonhttp://localhost:${port}`);
});
In the `app.js` file, we import the `Note` model from`noteModel.js`, and we can now use the `Note`
model to perform CRUD operations (e.g., `find`, `create`, `update`, `delete`) onthe `Note` collection
in the MongoDBdatabase.
Remember to replace `'your-mongodb-uri'` with your actual MongoDB connection string.
Additionally, ensure that the `noteModel.js` file and the `app.js` file are in the same directory or
provide the correct relative pathwhen importing the`Note` model.

18
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-4:
ProblemStatement1:
WriteaprogramtoperformvariousCRUD(Create-Read-Update-Delete)operationsusingMongooselibrary
functions.
Node.jsprogramthatusestheMongooselibrarytoperformCRUDoperationsonaMongoDBdatabase.Before
runningthisprogram,makesuretoinstallthenecessarydependenciesbyrunning npminstallmongoose
i
n your project directory.
constmongoose=require('mongoose')
//ConnecttoMongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase',{useNewUrlParser:true,useUnifiedTopol
ogy:true });
constdb=mongoose.connection;
// Define a schema for the data
constuserSchema= new
mongoose.Schema({ name: String,
email:String,
age: Number
});
//Createamodelbasedontheschema
constUser=mongoose.model('User',userSchema);
//Createoperation
constcreateUser= async (name, email,age)
=>{ const user = new User({ name,
email,age }); await user.save();
console.log('Usercreated:',user);
};
//ReadoperationconstgetUs
ers= async () =>{ const
users = await User.find();
console.log('Users:',users);
};

//Updateoperation

constupdateUser=async(id,newData)=>{

const user = awaitUser.findByIdAndUpdate(id,newData, { new: true


}); console.log('Userupdated:', user);

19
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

};
// Delete
operationconstdeleteUser=
async (id) => {
const user = awaitUser.findByIdAndDelete(id);
console.log('Userdeleted:', user);
};

//Exampleusage

asyncfunctionmain(){

//Create

awaitcreateUser('JohnDoe','john@example.com',25);

//Read

awaitgetUsers();

//Update

constuserIdToUpdate = '<user_id_to_update>';
constnewData = { age: 26 };
awaitupdateUser(userIdToUpdate,newData);

// Read again after


update await getUsers();
//Delete

constuserIdToDelete=
'<user_id_to_delete>'; await
deleteUser(userIdToDelete);
// Read again after delete
await getUsers();
// Disconnect from MongoDB
mongoose.disconnect();
}

main().catch(err=>console.error(err));

20
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:
ToimplementthedescribedAPIsforfetchingandupdatingnotesinamyNotesapplication,youcanusea
Node.jsframeworklikeExpressalong withMongoose for MongoDB interactions.Below is a simple
example using Expressand Mongoose:
1. Install the necessary
dependencies: npm installexpress
mongoose
2. Createa server.js filewiththefollowingcode:
constexpress=require('express');co
nst mongoose=
require('mongoose');
constbodyParser=require('body-parser');

const app =
express(); const port
= 3000;

//ConnecttoMongoDB
mongoose.connect('mongodb://localhost:27017/myNotesDB',{useNewUrlParser:true,useUnifiedTopo
logy:true });
constdb=mongoose.connection;

// Define a schema for the notes


constnoteSchema= new
mongoose.Schema({ title: String,
content:String
});

//Createamodelbasedontheschema
const Note = mongoose.model('Note',noteSchema);
app.use(bodyParser.json());
// Fetch note detailsbased on
noteIDapp.get('/notes/:noteID',async
(req, res) => { constnoteID =
req.params.noteID;

try{
constnote=awaitNote.findById(noteID);

21
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

if (note) {
res.json(note);
}else{
res.status(404).json({message:'Notenotfound'});
}
}catch(error){
res.status(500).json({message:'Internalservererror'});
}
});

// Update note detailsbased on


noteIDapp.put('/notes/:noteID', async
(req, res) => { constnoteID =
req.params.noteID;
const{title,content}=req.body;
try{
constupdatedNote= await Note.findByIdAndUpdate(
noteID,
{title,content},
{new:true}
);

if (updatedNote)
{
res.json(updatedNot
e);
}else{
res.status(404).json({message:'Notenotfound'});
}
}catch(error){
res.status(500).json({message:'Internalservererror'});
}
});

// Start the server


app.listen(port,() =>
{
console.log(`Serverisrunningonhttp://localhost:${port}`);
});

22
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement3:
Writeaprogramtoexplainsessionmanagementusingcookies.
Ina real-world application, youwould wantto implementmore robustsecuritymeasuresandpossibly use a
dedicated sessionmanagementlibrary.
1. First,installthenecessarydependencies:
npm install express cookie-parser
2. Createa filewiththefollowingcode:
const express = require('express');
server.js
constcookieParser = require('cookie-parser');

constapp=express(); const
port = 3000;

app.use(express.urlencoded({extended:true}));
app.use(cookieParser());

//Middlewaretocheckiftheuser isauthenticated
constisAuthenticated= (req, res, next) =>{ constuserCookie
= req.cookies.user;

if(userCookie&&userCookie==='authenticated'){
next();//Userisauthenticated,proceedtothenextmiddlewareorroute
}else{
res.status(401).send('Unauthorized');//Userisnotauthenticated
}
};

23
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Loginroutesetsacookietoauthenticatethe user
app.post('/login', (req, res) => {
const{username,password}=req.body;

//Inarealapplication,youwouldperformproperauthenticationhere if
(username=== 'user' && password === 'password') {
res.cookie('user', 'authenticated');
res.send('Loginsuccessful');
} else {
res.status(401).send('Loginfailed');
}
});

// Protected route that requires authentication


app.get('/dashboard',isAuthenticated,(req,res)=>{
res.send('Welcome to the dashboard!');
});

//Logout routeclearstheauthenticationcookie
app.post('/logout', (req, res) => {
res.clearCookie('user');
res.send('Logoutsuccessful');
});

// Start the server


app.listen(port,()=>{
console.log(`Serverisrunningonhttp://localhost:${port}`);
});
ProblemStatement4:
Writeaprogramtoexplainsessionmanagementusingsessions.
Theexpress-sessionlibraryiscommonlyusedforsessionmanagementinExpressapplications. Below is a
simple example to illustrate sessionmanagementusing express-session.
1. First,installthenecessarydependencies:
npm install express express-session
2. const express = require('express');
const session=require('express-session');

constapp=express(); const
port = 3000;

24
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Usetheexpress-sessionmiddleware
app.use(session({
secret:'mySecretKey', resave: false,
saveUninitialized: true,
cookie:{ secure:false} //SettotrueifusingHTTPS
}));

//Middlewaretocheckiftheuser isauthenticated constisAuthenticated=


(req, res, next) => {
if(req.session&&req.session.user==='authenticated'){
next();//Userisauthenticated,proceedtothenextmiddlewareorroute
}else{
res.status(401).send('Unauthorized');//Userisnotauthenticated
}
};

//Loginroutesetstheusersessiontoauthenticate
app.post('/login', (req, res) => {
const{username,password}=req.body;

//Inarealapplication,youwouldperformproperauthenticationhere if
(username=== 'user' && password === 'password') { req.session.user
= 'authenticated';
res.send('Loginsuccessful');
} else {
res.status(401).send('Loginfailed');
}
});

// Protected route that requires authentication


app.get('/dashboard',isAuthenticated,(req,res)=>{
res.send('Welcome to the dashboard!');
});

25
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Logout routedestroystheusersession
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error(err);
}

res.send('Logoutsuccessful');

});

});

// Start the server


app.listen(port,()=>{
console.log(`Serverisrunningonhttp://localhost:${port}`);

});

 The express-session middleware is used to handle sessions. It is configured witha secretkey, and
the session data is stored in memory by default (for simplicity; in production, you might use a more
robust store like Redis).
 The/login routesetstheuserpropertyinthesessionto'authenticated'upon successfullogin.

 The/dashboardrouteisprotectedbytheisAuthenticatedmiddleware,whichchecksiftheuser
propertyinthesessionissetto 'authenticated'.

 The/logoutroute destroystheentire sessionuponlogout.

26
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-5:

ProblemStatement1:

Onthepage,displaythepriceofthemobile-basedinthreedifferentcolors.Insteadofusingthe numberinour
code,representthem bystring values likeGoldPlatinum,PinkGold, SilverTitanium.

<!DOCTYPEhtml>

<htmllang="en">

<head>

<metacharset="UTF-8">

<metaname="viewport"content="width=device-width,initial-scale=1.0">

<title>MobilePrices</title>

<style>

/*Definestylesfordifferentcolors*/

.gold-platinum{color: gold;}

.pink-gold{color:pink;}

.silver-titanium{color:silver;}

</style>

</head>

<body>

27
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

<h1>MobilePrices</h1>

<divid="goldPlatinumPrice"class="gold-platinum"></div>

<divid="pinkGoldPrice"class="pink-gold"></div>

<divid="silverTitaniumPrice"class="silver-titanium"></div>

<script>

//Definepricevaluesasstringconstants constGoldPlatinum
= "GoldPlatinum"

28
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

constPinkGold= "PinkGold";
constSilverTitanium = "SilverTitanium";

//Functiontodisplaypricesdynamically
functiondisplayPrices() {
constgoldPlatinumPriceElement= document.getElementById("goldPlatinumPrice");
constpinkGoldPriceElement= document.getElementById("pinkGoldPrice");
constsilverTitaniumPriceElement= document.getElementById("silverTitaniumPrice");

// Set prices for different colors


constgoldPlatinumPrice="GoldPlatinumPrice: $1000";
constpinkGoldPrice = "Pink Gold Price: $900";
constsilverTitaniumPrice ="SilverTitaniumPrice:$850";

// Display prices in the respective elements


goldPlatinumPriceElement.textContent= goldPlatinumPrice;
pinkGoldPriceElement.textContent= pinkGoldPrice;
silverTitaniumPriceElement.textContent= silverTitaniumPrice;
}

//Callthefunction to displayprices
displayPrices();
</script>

</body>

</html>

29
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:

Define an arrow function inside the event handler to filter the productarraywiththe selected product
object using the productId received by the function. Pass the selected product object to the next
screen.

<!--Assumingyouhaveabuttonorsomeclickableelementtriggeringtheevent-->

<buttonid="selectProductButton">SelectProduct</button>

<script>

//Samplearrayofproducts
const products = [
{productId:1,productName:'ProductA',price:100},

{productId:2,productName:'ProductB',price:150},

{productId:3,productName:'ProductC',price:120}

//...more products

];

// Event handler for the buttonclick


consthandleProductSelection=(productId)=>{
// Use arrow function to filter the arraybased on the selected product ID
constselectedProduct=products.find(product=>product.productId===productId);

if(selectedProduct){

30
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Assumingyouwanttopasstheselectedproducttothenextscreen(console.logfor demonstration)

console.log('SelectedProduct:',selectedProduct);

//Addcodeheretonavigatetothenextscreenorperformotheractions

}else{

console.error('Productnotfound!');

};

31
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

// Attach the event handler to the button click


document.getElementById('selectProductButton').addEventListener('click',()=>{
//Replace'selectedProductId'withthe actual productIDyouhave
constselectedProductId = 2; // For example, selecting Product B
handleProductSelection(selectedProductId);
});

</script>

ProblemStatement3:

Considerthatdeveloperneedstodeclareafunction-getMobileByVendorwhich acceptsstring as input


parameter and returns the list ofmobiles.

//Samplearrayofmobiles
const mobiles = [
{id:1,vendor:'Apple',model:'iPhone 12',price:999},

{id: 2,vendor: 'Samsung',model:'GalaxyS21',price:899},

{id:3,vendor:'Apple',model:'iPhoneSE',price:399},

//...more mobiles

];

// Function to get mobiles by vendor


constgetMobileByVendor=(vendor)=>{
//Filterthearraybasedonthevendorname

constmobilesByVendor = mobiles.filter(mobile =>mobile.vendor.toLowerCase() ===


vendor.toLowerCase());
returnmobilesByVendor;

32
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

};

//Example usage

constappleMobiles=getMobileByVendor('Apple');

33
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

console.log('Apple Mobiles:', appleMobiles);


constsamsungMobiles=getMobileByVendor('Samsung');
console.log('SamsungMobiles:', samsungMobiles);

ProblemStatement4:

Consider that developer needs to declare a manufacturer's arrayholding4 objects withidandpriceas a


parameter and needs to implement an arrow function - myfunctionto populate the id parameter of
manufacturersarraywhose price is greater than or equal

//Declarethemanufacturer'sarraywith4objectscontaining idand priceparameters let


manufacturers= [
{id:null, price:100},

{id:null,price:150},

{id:null, price:200},

{id:null, price:250}

];

//Implementanarrowfunction-myFunctiontopopulatethe idparameter
constmyFunction= (array, thresholdPrice) =>{
array.forEach(manufacturer=> {
if(manufacturer.price>=thresholdPrice){

//Populatetheidparameterbasedonthecondition

//Forsimplicity,let'susethe priceastheidinthis example

34
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

manufacturer.id= manufacturer.price;
}

});

};

//CallmyFunctionwiththemanufacturersarrayandathresholdprice

35
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

myFunction(manufacturers,150);

//Output themodifiedmanufacturersarray console.log(manufacturers);


//Output
[
{id:null, price:100},

{id:150,price:150},

{id:200,price:200},

{id:250,price:250}

ProblemStatement5:

Declare a function - getMobileByManufacturer with two parameters namely manufacturer and id,
where manufacturer value should passed as Samsung and id parameter should be optional while
invoking the function,ifid is passed as 101 thenthis functionshoul

functiongetMobileByManufacturer(manufacturer,id=101){

//Logic tofetchmobiledetailsbasedonthemanufacturerandoptionalid

//Fordemonstration purposes,let'screateasampledataobject
constmobilesDatabase = {
Samsung:[

{id:100, model:'GalaxyS21', price:999 },

36
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

{id:101,model:'GalaxyNote20',price:1099},

//Addmore Samsungmobilesasneeded

],

//Addmoremanufacturersandtheirmobiles asneeded

};

//Checkiftheprovidedmanufacturerexistsinthedatabase

37
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

if(manufacturerinmobilesDatabase) {

constmobiles=mobilesDatabase[manufacturer];

//Findthe mobile withthespecifiedidorusethedefault id(101)


constselectedMobile = mobiles.find(mobile => mobile.id === id);

if (selectedMobile) {
returnselectedMobile;
}else{

return`Nomobilefoundwithid${id}formanufacturer${manufacturer}`;

}else{

return`Manufacturer${manufacturer}notfoundinthedatabase`;

//Example usage:

constmobileDetails=getMobileByManufacturer('Samsung',101);
console.log(mobileDetails);

38
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Output

{id:101,model:'GalaxyNote20',price:1099}

39
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-6:

ProblemStatement1:

ImplementbusinesslogicforaddingmultipleProductvaluesintoacartvariablewhichistypeofstringarray.

class ShoppingCart{
privatecart:string[]=[];
//Addasingleproductto the cart
addProduct(product: string) {
this.cart.push(product);
}

//Addmultipleproducts tothe cart


addProducts(products: string[]) {
this.cart = this.cart.concat(products);
}

//Getthecurrent contentsofthe cart


getCartContents(){
returnthis.cart;

//Exampleusage

constshoppingCart=new ShoppingCart();

// Adding a single product


shoppingCart.addProduct("ProductA");
//Addingmultipleproducts

constproductsToAdd =["ProductB","ProductC","ProductD"];
shoppingCart.addProducts(productsToAdd);
// Getting the current contentsofthe cart
constcartContents=shoppingCart.getCartContents();
console.log("Cart Contents:",cartContents);

40
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:

Declareaninterfacenamed-ProductwithtwopropertieslikeproductIdandproductNamewithanumberand
stringdatatypeand need to implementlogicto populatethe Product details.
//DeclaretheProductinterface
interface Product {
productId: number;
productName:string;
}

//Functionto populateproductdetails

functionpopulateProductDetails(id:number,name: string):Product{

//CreateanewProductobject const
product: Product = { productId: id,
productName:name,

};

//Returnthepopulatedproduct
return product;
}

//Example usage

constproduct1:Product=populateProductDetails(1,"ProductA");
constproduct2:Product=populateProductDetails(2,"ProductB");
// Display product details
console.log("Product1:",product1);
console.log("Product2:",product2);

41
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement3:

Declareaninterfacenamed-ProductwithtwopropertieslikeproductIdandproductNamewiththenumber and
stringdatatypeand need to implementlogicto populatethe Product details.
//DeclaretheProductinterface
interface Product {
productId: number;
productName:string;
}

//Functiontopopulateproductdetails

functionpopulateProductDetails(id:number,name:string):Product{

//CreateanewProductobject const
product: Product = { productId: id,
productName:name,

};

//Returnthepopulatedproduct
return product;
}

//Example usage

constproduct1:Product=populateProductDetails(1, "ProductA");
constproduct2:Product=populateProductDetails(2,"ProductB");
// Display product details
console.log("Product1:",product1);
console.log("Product2:",product2);
ProblemStatement4:

Declareaninterfacewithfunctiontypeandaccessitsvalue.

//Declareaninterfacewithafunctiontype
interface MyFunction{
(param1:number,param2:string):void;

42
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

// Implementthe interface with a function


constmyFunctionImplementation:MyFunction=(num,str)=>{
console.log(`Number:${num},String: ${str}`);
};

//Accessthefunction

myFunctionImplementation(42,"Hello,TypeScript!");

1. TheMyFunctioninterfaceisdeclaredwithafunctiontypethattakestwoparameters
(param1oftype numberand param2oftype string) and returns void.
2. ThemyFunctionImplementationvariableisdeclaredandassigneda functionthatmatches the
signaturedefined intheMyFunctioninterface.
3. YoucanthenaccessthefunctionbycallingmyFunctionImplementationwiththe appropriate
arguments.

43
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-7:

ProblemStatement1:
InstallingMongoDBLocally:
1. DownloadMongoDB:
 VisittheMongoDBdownloadpage:MongoDBDownloadCenter.
 Chooseyouroperatingsystemand downloadtheappropriateversion.
2. InstallMongoDB:
 Followtheinstallationinstructionsforyouroperatingsystem.
 For Windows,theinstaller will guideyouthroughtheinstallationprocess.Makesure to
install MongoDBas a service.
3. Start MongoDB:
 Once the installationiscomplete,starttheMongoDBservice.OnWindows,thismay
involve starting the service through the Services application.
4. VerifyInstallation:
 Open acommandprompt orterminalandrun thefollowing command to connect to the
MongoDBserver:
mongo
 ThisshouldconnectyoutotheMongoDBshell.
ConfiguringMongoDB Atlas:
1. CreateaMongoDBAtlasAccount:
 VisittheMongoDBAtlaswebsite:MongoDBAtlas.
 Clickon"GetStartedFree"tocreatean account.
2. CreateaNewCluster:
 Afterloggingin,clickon"BuildaCluster."
 Chooseyourpreferredcloudprovider,region,andothersettings.
 Clickon"CreateCluster"tostartthedeployment.
3. ConfigureNetworkAccess:
 Intheleftsidebar,clickon"DatabaseAccess"andcreateanewdatabase user.
 Intheleftsidebar,clickon"NetworkAccess"andaddyourIPaddresstotheIP Whitelist.
4. ConnecttoYourCluster:
 Intheleftsidebar,clickon"Clusters"andthenclickon"Connect"foryourcluster.
 Choose"ConnectYourApplication"andcopytheconnectionstring.
5. UpdateYourApplicationConnectionString:
 Ifyou'reusingaNode.jsapplication,forexample,replacethe<password>,
<dbname>,and other placeholders inthe connectionstringwithyour actual credentials and database
name.

44
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

6. TesttheConnection:
 ConnectyourapplicationtoMongoDBAtlasusingtheupdatedconnectionstring.
 VerifythatyourapplicationcansuccessfullyconnecttotheMongoDBAtlas cluster.

ProblemStatement2:
WriteMongoDBqueriestoperformCRUDoperationsondocumentusinginsert(),find(),update(),remove()

InsertDocuments:
//Insertasingledocumentintoacollection db.products.insert({
name:"Laptop",
price: 1200,
category:"Electronics"
});

//Insertmultipledocumentsintoacollection db.products.insertMany([
{name:"Smartphone",price:600,category:"Electronics"},
{name:"Book",price:20,category:"Books"}
]);

1. FindDocuments:
//Findalldocuments inthe"products" collection
db.products.find();

//Finddocumentsthatmatch aspecificcondition
db.products.find({ category:"Electronics" });

// Find one document


db.products.findOne({name:"Laptop"});

2. UpdateDocuments:
//Updateasingledocument
db.products.update({name:"Laptop"},{$set:{price:1300}});

45
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Updatemultiple documents
db.products.update({category:"Electronics"},{$inc:{price:50}},{multi:true });

//Update orinsertadocumentifitdoesn'texist
db.products.update(
{name:"Tablet"},
{ $set:{price:300,category:"Electronics"}},
{upsert:true}
);

3. Remove Documents:
// Remove a single document
db.products.remove({name:"Book"});

//Removealldocuments thatmatch aspecificcondition


db.products.remove({ category: "Electronics" });

//Removealldocuments fromthe "products"collection


db.products.remove({});

46
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-8:

ProblemStatement1:

WriteMongoDBqueriestoCreateanddropdatabasesandcollections.

1. CreateDatabase:

//Createanewdatabasenamed "mydatabase" use


mydatabase
Thiscommandswitchestothespecifieddatabase,andifitdoesn'texist,MongoDBcreatesit.

2. DropDatabase:

//Drop(delete)thecurrentdatabase
db.dropDatabase()
3. CreateCollection:

//Createanewcollectionnamed "mycollection" inthecurrent database db.createCollection("mycollection")


Thiscommandcreatesanewcollectioninthecurrentdatabase.

4. DropCollection:

//Drop(delete)the"mycollection" collection
db.mycollection.drop()
Thiscommandpermanentlydeletesthespecifiedcollection.

ProblemStatement2:

Write MongoDBqueriestoworkwithrecordsusingfind(),limit(),sort(),createIndex(),aggregate().

1. FindDocuments:

47
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

//Findalldocuments inthe"mycollection"collection
db.mycollection.find()
//Finddocumentsthatmatch aspecificcondition
db.mycollection.find({category:"Electronics"})

48
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

// Find one document


db.mycollection.findOne({name: "Laptop" })
2. LimitDocuments:

//Findthefirst5documentsinthe"mycollection"collection
db.mycollection.find().limit(5)
3. SortDocuments:

db.mycollection.find().sort({price:1})

//Findalldocumentsinthe "mycollection"collectionand sortthem bypriceindescendingorder


db.mycollection.find().sort({ price: -1 })

4. CreateIndex:

//Createanindex onthe "name"fieldofthe "mycollection"collection


db.mycollection.createIndex({name: 1 })

5. Aggregate:

//Usethe aggregate frameworktocalculatetheaveragepricepercategory


db.mycollection.aggregate([
{

$group:{

_id: "$category",
avgPrice:{$avg:"$price"}
}

},

49
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

$sort: {
avgPrice:-1
}

])

50
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-9:
ProblemStatement1:

ModuleName:AngularApplicationSetup
Observethelinkhttp://localhost:4200/welcomeonwhichthemCartapplicationis running.Performthe
belowactivitiestounderstandthe featuresofthe application.

1.InstallNode.jsandnpm:EnsurethatyouhaveNode.jsandnpm (Node Package Manager) installed on


your machine.YoucandownloadandinstallthemfromtheofficialNode.jswebsite:Node.js.

2.InstallAngularCLI: Openaterminalorcommandpromptandrunthefollowingcommandtoinstallthe
AngularCLI globallyon your machine:
npminstall-g@angular/cli

3.ClonethemCartRepository: If the mCart application is hosted on a version control platform like


GitHub,youcanclonetherepositorytoyourlocalmachineusing
aGitcommand.Navigatetothedirectorywhereyou want to store the project and run:
gitclone<repository_url>Replace<repository_url> withtheactual URLofthemCartrepository.

4.NavigatetotheProjectDirectory: Changeintotheprojectdirectoryusingthe cd command:


cdmCart

5.InstallDependencies: Installtheprojectdependenciesusingthefollowingcommand:
npminstall

6.RuntheApplication: StarttheAngulardevelopmentserverwiththefollowingcommand:
ngserve

athttp://localhost:4200.
Thiswillcompiletheapplicationandstartadevelopmentserver.Bydefault,theapplicationwillbeaccessible

7.ExploretheApplication:Openyourwebbrowserandgoto http://localhost:4200/welcome toviewthe


mCartapplication.Explorethedifferentfeaturesandfunctionalitiesprovidedbytheapplication.Youmight
finda landingpageor a welcomescreen at the specifiedURL.

51
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement2:

ModuleName:ComponentsandModules
CreateanewcomponentcalledhelloandrenderHelloAngularonthepage.
1.OpenaTerminalorCommandPrompt: Openaterminalorcommandpromptintheprojectdirectory
whereyouwanttocreatethenewcomponent.

2.GenerateaNewComponent: RunthefollowingAngularCLIcommandtogenerateanewcomponent
named"hello":
nggeneratecomponenthello
src/app
Thiscommandcreatesanewfoldernamed hello inthe directorywiththenecessaryfilesforthe
Angularcomponent.

3.OpentheComponentFile: Navigateto the newly created component


cdsrc/app/hello folder: file in your preferred code editor.
Openthe hello.component.ts
Replacethecontentofthe file with
thefollowing
4.UpdatetheComponentTemplate:
code hello.component.html
:

<p>HelloAngular</p>

Thissimpletemplatewillrenderthetext"HelloAngular"onthepage.

5.UsetheComponentinaModule: Openthe app.module.ts fileinthe src/app directory.Importthe


HelloComponent andaddittothe declarations
arrayinthe@NgModuledecorator:
//...otherimports
import{HelloComponent}from'./hello/hello.component';

@NgModule({
declarations:[
//...othercomponents
HelloComponent,
],
//...otherconfigurations
})

52
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

6.RendertheComponentinaTemplate: Openthe fileinthe directory.


Replaceitscontentwiththefollowingcodetoincludethe app.component.ht
<app-hello></app-hello> ml
Thiscodewillrenderthe hello
hell component:
componentwithintheapp src/app
o

component'stemplat
e.

7.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing

ngserve
command:
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee"Hello Angular"renderedonthe
page.

53
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement3:

ModuleName:ElementsofTemplateAddaneventtothehellocomponenttemplate and when it is


clicked,itshould change the courseName.
Toachievethis,youcanaddaclickeventtothe"HelloAngular"textinthe hello.component.html file.When
thetextisclicked,itwilltriggerafunctionthatchangesthe courseName property.Followthesesteps:

1.Updatehello.component.ts: Openthe hello.component.ts


fileinyourcodeeditorandaddanewproperty
courseName )andamethod( changeCourseName ):
(

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

@Component({ selector:
'app-hello',
templateUrl: './hello.component.html',
styleUrls:['./hello.component.css']
})

export class HelloComponent{ courseName:


string = 'Angular';

changeCourseName(){this.courseName =
'New Course Name';
}

Openthe fileandaddaclickeventtothe"Hello
2.Updatehello.component.html: hello.component.html
Angular"text
:

<p(click)="changeCourseName()">Hello{{courseName}}</p>

Inthisexample,the (click) eventisboundtothe changeCourseName method.Whenthetextisclicked,the


methodwillbecalled,andthe courseName propertywillbeupdated.

54
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

55
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

3.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:

Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee"HelloAngular"displayedon
the page.Clickingon itshouldchangethe textto "HelloNew Course Name".
Now,your hello componentrespondstoaclickeventandupdatesthe propertyaccordingly.
courseName

ProblemStatement4:

ModuleName:ChangeDetectionprogressivelybuildingthePoolCarzapplication.
Let'sprogressivelybuildasimple"PoolCarz"applicationandexplorechangedetectioninAngular.We'llcreat
e acomponentthatdisplaysalistofcarsandallowsuserstoaddnewcarstothelist.

src/app
1.CreateaCarModel: Createafilenamed car.model.ts inthe directorywiththefollowingcontent:
exportinterfaceCar{
id:number;
make:string;
model:string;
year:number;
}

2.CreateaCarService: Generateaservicetomanagethelistofcars.Runthefollowingcommandinthe

nggenerateservicecar
terminal:
Openthegeneratedcar.service.tsfileandimplementabasicservicethatinitializesandmanagesthelistof cars.

//car.service.ts
import{Injectable}from'@angular/core';
import{Car}from'./car.model';

56
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

@Injectable({
providedIn:'root',
})
exportclassCarService{
privatecars:Car[]=[];

getCars():Car[]{
returnthis.cars;
}

addCar(car:Car):void{
this.cars.push(car);

57
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

}
}

3.CreateaCarComponent: Generateacomponenttodisplaythelistofcarsandallowuserstoaddnewcars.
Runthefollowingcommandintheterminal:
nggeneratecomponentcar-list
Openthegenerated car-list.component.ts
//car-list.component.ts fileandimplementthecomponentlogic.
import{Component}from'@angular/core';
import{CarService}from'../car.service';
import{Car}from'../car.model';

@Component({
selector:'app-car-list',
templateUrl:'./car-list.component.html',
styleUrls:['./car-list.component.css'],
})
exportclassCarListComponent{
cars:Car[]=[];
newCar:Car={id:0,make:'',model:'',year:0};

constructor(privatecarService:CarService){
this.cars=carService.getCars();
}

addCar():void{
this.carService.addCar({...this.newCar,id:this.cars.length+1});
this.newCar={id:0,make:'',model:'',year:0};

58
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

}
}

Openthe fileandupdateittodisplaythelist
4.UpdateCarComponentTemplate: car-list.component.html
ofcarsandaformtoaddnewcars.

<!--car-list.component.html-->
<h2>PoolCarz</h2>

<ul>
<li*ngFor="letcarofcars">{{car.make}}{{car.model}}({{car.year}})</li>
</ul>

<div>
<h3>AddaNewCar</h3>
<form(ngSubmit)="addCar()">

59
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

<label>Make:<input[(ngModel)]="newCar.make"/></label>
<label>Model:<input[(ngModel)]="newCar.model"/></label>
<label>Year:<inputtype="number"[(ngModel)]="newCar.year"/></label>
<buttontype="submit">AddCar</button>
</form>
</div>
app.module.ts

Note:Makesureyouhave FormsModule importedinyour tousetwo-waydatabindingwith

ngModel.

Openthe fileandincludethe
5.UpdateAppComponentTemplate: app.component.html app-car-list
component
<!--app.component.html--
>
<div>
<app-car-list></app-car-
list>
</div>.
6.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing

ngserve
command:

Openyourwebbrowserandnavigatetohttp://localhost:4200. Youshouldseethe"PoolCarz" application


displayinganemptylistofcarsandaformtoaddnewcars.Tryaddingcars,andyoushouldseethelist
updatingdynamically.
ThisexampledemonstrateshowAngular'schangedetectionworks.Whenthe carService updatesthelistof
cars, Angularautomaticallydetects the changeand updates the
viewaccordingly.

60
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

Excersice-10:
ProblemStatement1:

CourseName:AngularJS
ModuleName:StructuralDirectives-ngIfCreatealoginformwithusernameand
passwordfields.Iftheuserentersthecorrectcredentials,itshouldrendera"Welcome
<>"messageotherwiseitshouldrender"InvalidLogin!!!Pleasetryagain..."message.

TocreatealoginformwithAngularusingthe ngIf structuraldirective,followthesesteps:


1.CreateaLoginComponent: Generateanewcomponentfortheloginfunctionality.Runthefollowing
commandinyourterminal:
nggeneratecomponentlogin
Thiswillcreateanewfoldernamed login inthe src/app directorywiththenecessaryfiles.

Openthe fileandimplementthelogin form:


2.UpdateLoginComponentHTML:
login.component.html
<!--login.component.html-->
<h2>Login</h2>
<form(ngSubmit)="login()">
<label>Username:<input[(ngModel)]="username"name="username"/></label>
<br/>
<label>Password: <input type="password" [(ngModel)]="password"
name="password" /></label>
<br/>
<buttontype="submit">Login</button>
</form>

<div*ngIf="isLoggedIn;elseinvalidLogin">
<p>Welcome{{username}}!</p>
</div>
<ng-template#invalidLogin>
<p>InvalidLogin!!!Pleasetryagain...</p>
</ng-template>
In thistemplate:
Weusetwo-way databinding ([(ngModel)])tobindtheinputfieldstothe
properties.
(ngSubmit) login()
username and password
61
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Theformhasa eventthatcallsthe method.
ngIf
Weusethe directivetoconditionallyrendereitherthewelcomemessageortheinvalidlogin
message.

3.UpdateLoginComponentTypeScript: Openthe login.component.ts fileandimplementthelogin logic:

//login.component.ts
import{Component}from'@angular/core';

62
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

@Component({ selector:
'app-login',
templateUrl:'./login.component.html',
styleUrls:['./login.component.css'],
})
export class LoginComponent{
username: string = '';password:
string = '';
isLoggedIn:boolean=false;

login():void{
//Replacethiswithyouractualauthenticationlogic
// For simplicity,we'll consider it a successful loginif both fields are non-emptyif
(this.username&&this.password) {
this.isLoggedIn=true;
} else {
this.isLoggedIn= false;
}
}
}
Note:Inareal-worldscenario,youwouldperformactualauthentication,possiblywithaserviceorAPIcall.

4.IncludeLoginComponentinAppModule: Openthe app.module.ts fileandincludethe LoginComponent


inthe declarations array.

//app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import {
NgModule} from '@angular/core';
import{FormsModule}from'@angular/forms';

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

@NgModule({
declarations: [AppComponent, LoginComponent],
imports: [BrowserModule,FormsModule], providers: [],
bootstrap:[AppComponent],
})
exportclassAppModule{}

63
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

5.RuntheApplication:IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:

ngserve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheloginform.Tryentering
somecredentials,andyou'llseeeitherthewelcomemessageortheinvalidloginmessagebasedonthelogicin
the login() method.
Thisexampledemonstratestheuseofthe ngIf directivetoconditionallyrendercontentbasedonthelogin
status.

ProblemStatement2:

ModuleName:ngForCreateacoursesarrayandrenderingitinthetemplateusing ngFor directive in a list


format.
Tocreateanarrayofcoursesandrenderitinthetemplateusingthe follow these steps: ngFor directive,
1. Update App Component TypeScript:Open thearray of app.component.ts fileanddefinean
courses in the component:
//app.component.ts
import{Component}from'@angular/core';

@Component({ selector:
'app-root',
templateUrl: './app.component.html', styleUrls:
['./app.component.css'],
})
exportclassAppComponent{
courses:string[]=['Angular','React','Vue','Node.js','Express'];
}
2. UpdateAppComponentTemplate: Openthe app.component.html fileandusethe
ngFor directivetoiterateoverthe courses arrayandrenderitinalistformat:
<!--app.component.html-->
<h2>Courses</h2>
<ul>
<li*ngFor="letcourseofcourses">{{course}}</li>
</ul>
In this template, the and*ngFor directive is used to loop over each course inthe courses array
render it inside an <li> element.

64
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

3. Run the Application:If your Angular development server is not running, start it with the following
command:
ngserve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee a list of courses rendered on
the page.

Thisexampledemonstrateshowtousethe ngFor directivetoiterateoveranarrayand


dynamicallyrendercontentinanAngulartemplate.Thelistofcoursesisdefinedinthe
componentanddisplayedusingthe *ngFor loopinthetemplate.

65
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

ProblemStatement3:

ModuleName:ngSwitch

DisplaythecorrectoptionbasedonthevaluepassedtongSwitchdirective.

The ngSwitch directiveinAngularisusedforconditionalrenderingbasedonthevalueofanexpression.Here's


anexampleofhowyoucanuse ngSwitch todisplaydifferentoptionsbasedonavariable'svalue:

Openthe fileanddefineavariabletocontrolthe
1.UpdateAppComponentTypeScript: app.component.ts
switch:
//app.component.t
s
import{Component}from'@angular/core';

@Component({
selector: 'app-root',
templateUrl:'./app.component.html'
, styleUrls:['./app.component.css'],
})
export class AppComponent{
selectedOption:string = 'option1';
}

2.UpdateAppComponentTemplate: Openthe app.component.html fileandusethe ngSwitch directiveto


conditionallyrenderdifferentoptionsbasedonthevalueofselectedOption:

<!--app.component.html-->
<h2>Options</h2>

<div[ngSwitch]="selectedOption">
<p*ngSwitchCase="'option1'">Option1isselected.</p>
<p*ngSwitchCase="'option2'">Option2isselected.</p>
<p*ngSwitchCase="'option3'">Option3isselected.</p>
<p*ngSwitchDefault>Selectanoption.</p>
</div>

66
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

<!--Changeoption-->
<div>
<label>Selectanoption:</label>
<select[(ngModel)]="selectedOption">
<optionvalue="option1">Option1</option>

<optionvalue="option2">Option2</option>
<optionvalue="option3">Option3</option>
</select>
</div>

67
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

In thistemplate:
<div> element,anditsvalueisboundtothe selectedOption
 The ngSwitch directiveisappliedtoa
variable.
 Differentcasesaredefinedusingthe *ngSwitchCase directive,andadefaultcaseisdefinedusing

*ngSwitchDefault.

 ThecontentinsideeachcaseisconditionallydisplayedbasedonthevalueofselectedOption.
 A <select> elementisincludedtochangethevalueof selectedOption dynamically.


3.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
comman
d: ng
serve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheoptionsdisplayedbasedon
the initial value ofselectedOption. Changing the value in the dropdown will update the displayed
option accordingly.
Thisexampledemonstrateshowtousethe ngSwitch directivetoconditionallyrenderdifferentoptionsbased

on the value of a variablein Angular.

ProblemStatement4:

ModuleName:CustomStructuralDirectiveCreateacustomstructuraldirectivecalled
'repeat'whichshouldrepeat the elementgivenanumberoftimes.
1.CreatetheDirective: Runthefollowingcommandinyourterminaltogenerateanewdirective:

nggeneratedirectiverepeat

Thiswillcreateanewfilenamed repeat.directive.ts inthe src/app directory.

repeat.directive.ts file and implement thecustom


Open
th
2.Implement the RepeatDirective: e
RepeatDirective .Thisdirectivewilltakeanumberasaninputandrepeatthehostelementthatmanytimesin
theDOM.

//repeat.directive.ts

import { Directive, Input, TemplateRef, ViewContainerRef } from


'@angular/core';

68
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

@Directive({

selector:'[appRepeat]',

})

exportclassRepeatDirective{

69
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

constructor(

private templateRef: TemplateRef<any>, private


viewContainer: ViewContainerRef
){}

@Input() set appRepeat(times: number) { for (let i


= 0; i< times; i++) {
this.viewContainer.createEmbeddedView(this.templateRef);

In thisdirective:

 appRepeat is aninputproperty that takes the numberof times to repeat.


 The TemplateRef representsthecontentoftheelementthedirectiveisappliedto.
 The ViewContainerRef isusedtomanagethecontainerwhereviewsareattached.

appRepeat
3.UsetheCustomDirective: Openthe app.component.html fileandusethe directivetorepeatan
elementa specifiednumber of times:
<!--app.component.html-->

<h2>RepeatDirectiveExample</h2>

<div*appRepeat="3">

<p>Thisparagraphwillberepeatedthreetimes.</p>

</div>

Inthisexample,the appRepeat directiveisappliedtoa <div> element,andtheparagraphinsideitwillbe


repeatedthreetimes
.

70
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

4.IncludetheDirectiveinAppModule: Openthe app.module.ts fileandincludethe inthe


declarations array: RepeatDirective

//app.module.ts

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


NgModule } from '@angular/core';

71
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual

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


import{RepeatDirective}from'./repeat.directive';

@NgModule({

declarations: [AppComponent, RepeatDirective],


imports: [BrowserModule],
providers:[],

bootstrap:[AppComponent],

})

exportclassAppModule{}
5.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:

ngserve

Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheparagraphrepeatedthr
ee
appRepeat
timesasspecifiedbythe directive.

Department of CSE(DS),PEC

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy