MST Lab Manual (R20)
MST Lab Manual (R20)
LAB MANUAL
Prepared by
CH. V. Gayathri
Assistant Professor
Pragati Engineering College
(Autonomous)
(Approved by AICTE, New Delhi & Affiliated to JNTUniversity, Kakinada)
1-378, ADB Road, Surampalem – 533 437
Department ofCSE(DS),PEC
MEANStackTechnologiesLabManual
INDEX
1
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
2
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-1:
Output:
array([1., 2., 3., 4.], dtype=float32)
Since NumPy arrays can contain only homogeneous datatypes, values will be upcast if the types
do not match:
np.array([1,2.0,3,4])
Output:
array([1., 2., 3., 4.])
Here, NumPy has upcast integer values to float values.
Array of Zeros
Array of zeros
NumPy lets you create an array of all zeros using the np.zeros() method. All you have to do is
pass the shape of the desired array:
np.zeros(5)
array([0., 0., 0., 0., 0.])
The one above is a 1-D array while the one below is a 2-D array:
np.zeros((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])
Array of ones
You could also create an array of all 1s using the np.ones() method:
np.ones(5,dtype=np.int32)
array([1, 1, 1, 1, 1])
Imatrix in NumPy
Another great method is np.eye() that returns an array with 1s along its diagonal
and 0s everywhere else.
An Identity matrix is a square matrix that has 1s along its main diagonal and 0s everywhere
else. Below is an Identity matrix of shape 3 x 3.
Note: A square matrix has an N x N shape. This means it has the same number of rows and
columns.
# identity matrix
np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
However, NumPy gives you the flexibility to change the diagonal along which the values have to
be 1s. You can either move it above the main diagonal:
# not an identity matrix
np.eye(3,k=1)
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
Or move it below the main diagonal:
4
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-2:
ProblemStatement1:
WriteaNode.jsmoduletoshowtheworkflowofModularizationofNodeapplication.
Highlights:
Creatingamodule
Loadingthemodule
Demosteps:
LetustryouthowtocreateandloadamoduleinaNodeapplication
Step1:CreateafileDBModule.jswithintheNodeJSfoldercreated earlier.
exports.authenticateUser=(username,password)=>{
if(username==="admin"&&password==="admin"){ return
"Valid User";
}elsereturn"InvalidUser";
};
Step2:Modifythefilehttpserver.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"andtheninvokingthefunctionnamed
"authenticateUser()".
Step3:Runthehttpserver.jsusingthenodecommand
5
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
OpenabrowserandnavigatetoURL"http://localhost:3000"andobservetheoutput
6
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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.Itprovidesadifferentwayto starta
Node.js application. It watches the application and whenever any change is detected, it restarts the
application.
Itisveryeasytogetstartedwiththistool.Toinstallitintheapplication,runthebelowcommand.
npminstallnodemon-g
Oncethe'nodemon'isinstalledinthemachine,theNode.jsservercodecanbeexecutedbyreplacing the
command"node" with "nodemon".
nodemonapp.js
Thusthe'nodemon'startstheapplicationinwatchmodeandrestarttheapplicationwhenanychangeis detected.
ConsiderasimpleNode.jscodeforcreatingawebserver.const
http = require("http");
var server = http.createServer((req, res) =>
{ res.write("HelloWorld!
Ihavecreatedmyfirstserver!"); res.end();
});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");
Observetheconsoleonstartingthenodemoninacommandpromptwindow.
7
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Nowopentheapplicationcodeanddochangesinthecodeasbelow.const http
= require("http");
var server = http.createServer((req, res) =>
{ console.log("Request URL is " + req.url);
res.write("HelloWorld!Ihavecreatedmyfirstserver!");
res.end();
});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");
Observetheconsolemessageinthecommandprompt.Nodemonautomaticallyrestartedtheserveron observing
changesin the code
Toavoidoverandoverrestartingofserverforsmallchangestoreflect.Itisimportant tohavean
automaticrestartoftheserver ofyour application. Use nodemon for this purpose.
8
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement3:
Createatextfilesrc.txtandaddthefollowingdatatoit.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('Filecreatedsuccessfullywithpromisifyandasync/await!');
} catch (err) {
console.log(err);
}
})();
Output:
Readingatextfile:
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:
9
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-3:
ProblemStatement1:
ImplementroutingfortheAdventureTrailsapplicationbyembeddingthenecessarycodeinthe
routes/route.js file.
Step1:Setuptheproject
Createanewdirectoryforyourprojectandnavigateintoit:
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
Step4:Createtheindex.jsfile
Inthe`index.js`file,setuptheExpressserverandincludethenecessaryroutes:
javascript
constexpress=require('express');
const app = express();
consttrailRoutes=require('./routes/trailRoutes');
//MiddlewaretoparserequestbodiesasJSONapp.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
10
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
constexpress=require('express');
constrouter= express.Router();
//Sampledatafortrails(replacethiswithyouractualdatasourceordatabase)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);
consttrail=trails.find((trail)=>trail.id===trailId);if (trail)
{
res.json(trail);
}else{ res.status(404).json({message:'Trailnotfound'
});
}
});
//Addmoreroutesasperyourapplication'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`.YoucantesttheroutesusingtoolslikePostmanorbymakingHTTP requests
inyourpreferred programminglanguage.
11
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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.
- Validatethedatato ensureit meetstherequiredcriteria(e.g.,checkingifthetitleandcontentare not
empty and within character limits).
2. *DisplayCustomizedErrorMessages*:
- Ifanyvalidationfails,generatespecificerrormessagesfortheuser.
- Displaytheseerrormessagesontheform,sotheuserknowswhatneedstobecorrected.
- Youcanuseserver-siderenderingorAJAXtohandle formsubmissionsandshowerrorswithout
refreshing the entire page.
3. *Logging*:
- Implement alogging mechanismtorecordimportant eventsanderrorsthatoccurduringthe form
submission process.
- Chooseanappropriatelogginglibraryorwritecustomloggingfunctionstohandledifferentloglevels
(e.g., info, warning, error).
- Logrelevantinformationsuchastheuser,timestamp,errormessage,andanyotheradditionaldetailsthat
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
#AssumingyouhavealreadysetuptheFlaskappandimportedrequiredmodulesimport logging
12
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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:
returnrender_template('form.html',error_message=error_message)
#Ifdataisvalid,savethepostinthedatabaseandredirecttothesuccesspage#(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 anerrormessage orsaves the post basedonthe validationresults.The
logging statementsare usedtokeep trackof important events inthe application.
13
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement3:
WriteaMongooseschematoconnectwithMongoDB.
ToestablishaconnectiontotheMongoDBdatabase,weneedtocreateaconnectionobjectusingMongoose.
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.
LetusnowestablishaconnectiontotheMongoDBdatabaseIntellectNotesforstoringdetailsusingthe
below code:
const mongoose= require('mongoose');
mongoose.connect('mongodb://localhost:27017/IntellectNotes',{
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify:false,
useUnifiedTopology:true,
})
Line2:HerewearespecifyingtheURIwherethedatawillbestored/retrieved.Thesecondparameter
{ 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'withtheactualconnectionstringtoyourMongoDBdatabase
constmongoURI= 'mongodb://localhost:27017/your-database-name';
14
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//ConnecttotheMongoDBdatabase
mongoose.connect(mongoURI,{
useNewUrlParser: true,
useUnifiedTopology:true,
})
.then(()=>console.log('MongoDBconnectedsuccessfully'))
.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,
},
});
// Createthe 'Note'modelusing 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'withtheactualconnectionstringtoyourMongoDBdatabase
constmongoURI= 'mongodb://localhost:27017/your-database-name';
15
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//ConnecttotheMongoDBdatabase
mongoose.connect(mongoURI,{
useNewUrlParser: true,
useUnifiedTopology:true,
})
.then(()=>console.log('MongoDBconnectedsuccessfully'))
.catch((err)=>console.error('ErrorconnectingtoMongoDB:',err.message));
required:true,
},
content: {
type:String,
required:true,
},
createdAt: {
type:Date,
default:Date.now,
},
});
// Createthe 'Note'modelusing the
'noteSchema'constNote=mongoose.model('Note',
noteSchema); module.exports= Note;
Now,inyourmainapplicationfile(e.g.,`app.js`),youcanusethe`Note`modelbyimportingitfromthe
`noteModel.js`file:
Javascript
16
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
const express=require('express');
constNote=require('./noteModel');//ImporttheNotemodelconst
app = express();
//Yourapplicationroutesandothermiddlewarecanbedefinedhere
//Forexample:
app.get('/notes',async(req,res)=>{try
{
//FetchallnotesfromtheMongoDBdatabaseusingtheNotemodel const
notes = await Note.find({});
//Respondwiththefetchednotes
res.json(notes);
}catch(err){
// Handle errors, e.g., send an error response
res.status(500).json({error:'Errorfetchingnotes'});
}
});
//Starttheserver
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` collectionin
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.
17
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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)
=>{constuser=newUser({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);
18
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
};
// Delete
operationconstdeleteUser=
async (id) => {
constuser=awaitUser.findByIdAndDelete(id);
console.log('Userdeleted:', user);
};
//Exampleusage
asyncfunctionmain(){
//Create
awaitcreateUser('JohnDoe','[email protected]',25);
//Read
awaitgetUsers();
//Update
constuserIdToUpdate='<user_id_to_update>';
constnewData = { age: 26 };
awaitupdateUser(userIdToUpdate,newData);
constuserIdToDelete=
'<user_id_to_delete>';await
deleteUser(userIdToDelete);
//Readagainafterdelete
await getUsers();
//DisconnectfromMongoDB
mongoose.disconnect();
}
main().catch(err=>console.error(err));
19
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement2:
ToimplementthedescribedAPIsforfetchingandupdatingnotesinamyNotesapplication,youcanusea
Node.jsframeworklikeExpressalongwithMongooseforMongoDBinteractions.Belowisasimple example
using Expressand Mongoose:
1. Install the necessary
dependencies:npminstallexpress
mongoose
2. Createa server.js filewiththefollowingcode:
constexpress=require('express');co
nst mongoose=
require('mongoose');
constbodyParser=require('body-parser');
const app =
express();constport
=3000;
//ConnecttoMongoDB mongoose.connect('mongodb://localhost:27017/myNotesDB',
{useNewUrlParser:true,useUnifiedTopo logy:true });
constdb=mongoose.connection;
//Createamodelbasedontheschema
constNote=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(noteI
D);
20
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
if (note) {
res.json(note);
}else{ res.status(404).json({message:'Notenotfound
'});
}
}catch(error)
{ res.status(500).json({message:'Internalservererror'});
}
});
if(updatedNote)
{
res.json(updatedNot
e);
}else{ res.status(404).json({message:'Notenotfound
'});
}
}catch(error)
{ res.status(500).json({message:'Internalservererror'});
}
});
21
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement3:
Writeaprogramtoexplainsessionmanagementusingcookies.
Inareal-worldapplication,youwouldwanttoimplementmorerobustsecuritymeasuresandpossiblyusea
dedicated sessionmanagementlibrary.
1. First,installthenecessarydependencies:
npm install express cookie-parser
2. Createa filewiththefollowingcode:
constexpress=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
}
};
22
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Loginroutesetsacookietoauthenticatetheuser
app.post('/login', (req, res) => {
const{username,password}=req.body;
//Inarealapplication,youwouldperformproperauthenticationhereif
(username=== 'user'&& password === 'password')
{ res.cookie('user', 'authenticated');
res.send('Loginsuccessful');
} else {
res.status(401).send('Loginfailed');
}
});
//Logout routeclearstheauthenticationcookie
app.post('/logout', (req, res) => {
res.clearCookie('user');
res.send('Logoutsuccessful');
});
constapp=express();const
port = 3000;
23
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Usetheexpress-sessionmiddleware
app.use(session({ secret:'mySecretKe
y',resave:false, saveUninitialized:
true,
cookie:{secure:false}//SettotrueifusingHTTPS
}));
//MiddlewaretocheckiftheuserisauthenticatedconstisAuthenticated=
(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');
}
});
24
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Logoutroutedestroystheusersession
app.post('/logout', (req, res) =>
{ req.session.destroy((err) => {
if (err) {
console.error(err);
}
res.send('Logoutsuccessful');
});
});
});
The express-session middleware is used to handle sessions. It is configured witha secretkey, andthe
session data is stored in memory by default (for simplicity; in production, you might use a more
robust store like Redis).
The/loginroutesetstheuserpropertyinthesessionto'authenticated'uponsuccessfullogin.
The/dashboardrouteisprotectedbytheisAuthenticatedmiddleware,whichchecksiftheuser
propertyinthesessionissetto 'authenticated'.
The/logoutroutedestroystheentiresessionuponlogout.
25
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-5:
ProblemStatement1:
Onthepage,displaythepriceofthemobile-basedinthreedifferentcolors.Insteadofusingthenumberinour
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>
26
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
<h1>MobilePrices</h1>
<divid="goldPlatinumPrice"class="gold-platinum"></div>
<divid="pinkGoldPrice"class="pink-gold"></div>
<divid="silverTitaniumPrice"class="silver-titanium"></div>
<script>
//DefinepricevaluesasstringconstantsconstGoldPlatinum
="GoldPlatinum"
27
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
constPinkGold= "PinkGold";
constSilverTitanium="SilverTitanium";
//Functiontodisplaypricesdynamically
functiondisplayPrices() {
constgoldPlatinumPriceElement= document.getElementById("goldPlatinumPrice");
constpinkGoldPriceElement= document.getElementById("pinkGoldPrice");
constsilverTitaniumPriceElement= document.getElementById("silverTitaniumPrice");
//Callthefunctiontodisplayprices
displayPrices();
</script>
</body>
</html>
28
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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}
//...moreproducts
];
if(selectedProduct){
29
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Assumingyouwanttopasstheselectedproducttothenextscreen(console.logfor demonstration)
console.log('SelectedProduct:',selectedProduct);
//Addcodeheretonavigatetothenextscreenorperformotheractions
}else{
console.error('Productnotfound!');
};
30
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
</script>
ProblemStatement3:
Considerthatdeveloperneedstodeclareafunction-getMobileByVendorwhichacceptsstringasinput
parameter and returns the list ofmobiles.
//Samplearrayofmobiles
const mobiles = [
{id:1,vendor:'Apple',model:'iPhone12',price:999},
{id:2,vendor:'Samsung',model:'GalaxyS21',price:899},
{id:3,vendor:'Apple',model:'iPhoneSE',price:399},
//...moremobiles
];
31
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
};
//Exampleusage
constappleMobiles=getMobileByVendor('Apple');
32
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement4:
//Declarethemanufacturer'sarraywith4objectscontainingidandpriceparameterslet
manufacturers= [
{id:null,price:100},
{id:null,price:150},
{id:null,price:200},
{id:null,price:250}
];
//Implementanarrowfunction-myFunctiontopopulatetheidparameter
constmyFunction= (array, thresholdPrice)
=>{ array.forEach(manufacturer=> {
if(manufacturer.price>=thresholdPrice){
//Populatetheidparameterbasedonthecondition
//Forsimplicity,let'susethepriceastheidinthisexample
33
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
manufacturer.id=manufacturer.price;
}
});
};
//CallmyFunctionwiththemanufacturersarrayandathresholdprice
34
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
myFunction(manufacturers,150);
//Outputthemodifiedmanufacturersarrayconsole.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){
//Logictofetchmobiledetailsbasedonthemanufacturerandoptionalid
//Fordemonstration purposes,let'screateasampledataobject
constmobilesDatabase = {
Samsung:[
{id:100,model:'GalaxyS21',price:999},
35
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
{id:101,model:'GalaxyNote20',price:1099},
//AddmoreSamsungmobilesasneeded
],
//Addmoremanufacturersandtheirmobilesasneeded
};
//Checkiftheprovidedmanufacturerexistsinthedatabase
36
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
if(manufacturerinmobilesDatabase){
constmobiles=mobilesDatabase[manufacturer];
if (selectedMobile) {
returnselectedMobile;
}else{
return`Nomobilefoundwithid${id}formanufacturer${manufacturer}`;
}else{
return`Manufacturer${manufacturer}notfoundinthedatabase`;
//Exampleusage:
constmobileDetails=getMobileByManufacturer('Samsung',101);
console.log(mobileDetails);
37
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Output
{id:101,model:'GalaxyNote20',price:1099}
38
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-6:
ProblemStatement1:
ImplementbusinesslogicforaddingmultipleProductvaluesintoacartvariablewhichistypeofstringarray.
class ShoppingCart{
privatecart:string[]=[];
//Addasingleproducttothecart
addProduct(product: string) {
this.cart.push(product);
}
//Getthecurrentcontentsofthecart
getCartContents(){
returnthis.cart;
//Exampleusage
constshoppingCart=newShoppingCart();
constproductsToAdd=["ProductB","ProductC","ProductD"];
shoppingCart.addProducts(productsToAdd);
// Getting the current contentsofthe cart
constcartContents=shoppingCart.getCartContents();
console.log("Cart Contents:",cartContents);
39
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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;
}
//Exampleusage
constproduct1:Product=populateProductDetails(1,"ProductA");
constproduct2:Product=populateProductDetails(2,"ProductB");
// Display product details
console.log("Product1:",product1);
console.log("Product2:",product2);
40
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement3:
Declareaninterfacenamed-ProductwithtwopropertieslikeproductIdandproductNamewiththenumberand
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;
}
//Exampleusage
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;
41
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Accessthefunction
myFunctionImplementation(42,"Hello,TypeScript!");
1. TheMyFunctioninterfaceisdeclaredwithafunctiontypethattakestwoparameters
(param1oftype numberand param2oftype string) and returns void.
2. ThemyFunctionImplementationvariableisdeclaredandassignedafunctionthatmatchesthe
signaturedefined intheMyFunctioninterface.
3. YoucanthenaccessthefunctionbycallingmyFunctionImplementationwiththeappropriate
arguments.
42
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-7:
ProblemStatement1:
InstallingMongoDBLocally:
1. DownloadMongoDB:
VisittheMongoDBdownloadpage:MongoDBDownloadCenter.
Chooseyouroperatingsystemanddownloadtheappropriateversion.
2. InstallMongoDB:
Followtheinstallationinstructionsforyouroperatingsystem.
ForWindows,theinstallerwillguideyouthroughtheinstallationprocess.Makesureto
install MongoDBas a service.
3. StartMongoDB:
Oncetheinstallationiscomplete,starttheMongoDBservice.OnWindows,thismay
involve starting the service through the Services application.
4. VerifyInstallation:
Openacommandpromptorterminalandrunthefollowingcommandtoconnecttothe
MongoDBserver:
mongo
ThisshouldconnectyoutotheMongoDBshell.
ConfiguringMongoDB Atlas:
1. CreateaMongoDBAtlasAccount:
VisittheMongoDBAtlaswebsite:MongoDBAtlas.
Clickon"GetStartedFree"tocreateanaccount.
2. CreateaNewCluster:
Afterloggingin,clickon"BuildaCluster."
Chooseyourpreferredcloudprovider,region,andothersettings.
Clickon"CreateCluster"tostartthedeployment.
3. ConfigureNetworkAccess:
Intheleftsidebar,clickon"DatabaseAccess"andcreateanewdatabaseuser.
Intheleftsidebar,clickon"NetworkAccess"andaddyourIPaddresstotheIPWhitelist.
4. ConnecttoYourCluster:
Intheleftsidebar,clickon"Clusters"andthenclickon"Connect"foryourcluster.
Choose"ConnectYourApplication"andcopytheconnectionstring.
5. UpdateYourApplicationConnectionString:
Ifyou'reusingaNode.jsapplication,forexample,replacethe<password>,
<dbname>,andotherplaceholdersintheconnectionstringwithyouractualcredentialsanddatabase name.
43
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
6. TesttheConnection:
ConnectyourapplicationtoMongoDBAtlasusingtheupdatedconnectionstring.
VerifythatyourapplicationcansuccessfullyconnecttotheMongoDBAtlascluster.
ProblemStatement2:
WriteMongoDBqueriestoperformCRUDoperationsondocumentusinginsert(),find(),update(),remove()
InsertDocuments:
//Insertasingledocumentintoacollectiondb.products.insert({
name:"Laptop",
price: 1200,
category:"Electronics"
});
//Insertmultipledocumentsintoacollectiondb.products.insertMany([
{name:"Smartphone",price:600,category:"Electronics"},
{name:"Book",price:20,category:"Books"}
]);
1. FindDocuments:
//Findalldocumentsinthe"products"collection
db.products.find();
//Finddocumentsthatmatchaspecificcondition
db.products.find({ category:"Electronics" });
2. UpdateDocuments:
//Updateasingledocument db.products.update({name:"Laptop"},{$set:
{price:1300}});
44
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Update orinsertadocumentifitdoesn'texist
db.products.update(
{name:"Tablet"},
{$set:{price:300,category:"Electronics"}},
{upsert:true}
);
3. RemoveDocuments:
// Remove a single document
db.products.remove({name:"Book"});
//Removealldocumentsthatmatchaspecificcondition
db.products.remove({ category: "Electronics" });
//Removealldocumentsfromthe"products"collection
db.products.remove({});
45
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-8:
ProblemStatement1:
WriteMongoDBqueriestoCreateanddropdatabasesandcollections.
1. CreateDatabase:
//Createanewdatabasenamed"mydatabase"use
mydatabase
Thiscommandswitchestothespecifieddatabase,andifitdoesn'texist,MongoDBcreatesit.
2. DropDatabase:
//Drop(delete)thecurrentdatabase
db.dropDatabase()
3. CreateCollection:
4. DropCollection:
//Drop(delete)the"mycollection"collection
db.mycollection.drop()
Thiscommandpermanentlydeletesthespecifiedcollection.
ProblemStatement2:
WriteMongoDBqueriestoworkwithrecordsusingfind(),limit(),sort(),createIndex(),aggregate().
1. FindDocuments:
46
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Findalldocumentsinthe"mycollection"collection
db.mycollection.find()
//Finddocumentsthatmatch aspecificcondition
db.mycollection.find({category:"Electronics"})
47
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//Findthefirst5documentsinthe"mycollection"collection
db.mycollection.find().limit(5)
3. SortDocuments:
db.mycollection.find().sort({price:1})
//Findalldocumentsinthe"mycollection"collectionandsortthembypriceindescendingorder
db.mycollection.find().sort({ price: -1 })
4. CreateIndex:
//Createanindexonthe"name"fieldofthe"mycollection"collection
db.mycollection.createIndex({name: 1 })
5. Aggregate:
//Usetheaggregateframeworktocalculatetheaveragepricepercategory
db.mycollection.aggregate([
{
$group:{
},
48
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
$sort: {
avgPrice:-1
}
])
49
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-9:
ProblemStatement1:
ModuleName:AngularApplicationSetup
Observethelinkhttp://localhost:4200/welcomeonwhichthemCartapplicationis running.Performthe
belowactivitiestounderstandthe featuresofthe application.
1.InstallNode.jsandnpm:EnsurethatyouhaveNode.jsandnpm(NodePackageManager)installedon
your machine.YoucandownloadandinstallthemfromtheofficialNode.jswebsite:Node.js.
2.InstallAngularCLI: Openaterminalorcommandpromptandrunthefollowingcommandtoinstallthe
AngularCLI globallyon your machine:
npminstall-g@angular/cli
4. NavigatetotheProjectDirectory:
Changeintotheprojectdirectoryusingthe cdcommand:
cdmCart
5. InstallDependencies:
Installtheprojectdependenciesusingthefollowingcommand:
npminstall
6. RuntheApplication:
StarttheAngulardevelopmentserverwiththefollowingcommand:
ngserve
athttp://localhost:4200.
Thiswillcompiletheapplicationandstartadevelopmentserver.Bydefault,theapplicationwillbeaccessible
50
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement2:
ModuleName:ComponentsandModules
CreateanewcomponentcalledhelloandrenderHelloAngularonthepage.
1.OpenaTerminalorCommandPrompt: Openaterminalorcommandpromptintheprojectdirectory
whereyouwanttocreatethenewcomponent.
2.GenerateaNewComponent: RunthefollowingAngularCLIcommandtogenerateanewcomponent
named"hello":
nggeneratecomponenthello
Thiscommandcreatesanewfoldernamed hello inthe src/app directorywiththenecessaryfilesforthe
Angularcomponent.
3.OpentheComponentFile:
Navigatetothenewlycreatedcomponent folder: file in your preferred code
cdsrc/app/hello
editor.
Openthe hello.component.ts
Replacethecontentofthe file with thefollowing
:c4o.UdpedatetheComponentTempl hello.component.html
<p>HelloAngular</p>
Thissimpletemplatewillrenderthetext"HelloAngular"onthepage.
5.UsetheComponentinaModule:
fileinthe directory.Importthe
Opentheapp
HelloComponent andaddittothe declarations the@NgModuledecorator:
.module.ts src/app
arrayin
//...otherimports
import{HelloComponent}from'./hello/hello.component';
@NgModule({
declarations:[
//...othercomponents
HelloComponent,
],
//...otherconfigurations
})
51
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
component'stemplat
e.
7.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
ngserve
command:
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee"HelloAngular"renderedonthe
page.
52
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement3:
ModuleName:ElementsofTemplateAddaneventtothehellocomponenttemplateandwhenitis
clicked,itshould change the courseName.
Toachievethis,youcanaddaclickeventtothe"HelloAngular"textinthe hello.component.html file.When
thetextisclicked,itwilltriggerafunctionthatchangesthe courseName property.Followthesesteps:
import{Component}from'@angular/core';
@Component({ selector:
'app-hello',
templateUrl:'./hello.component.html',
styleUrls:['./hello.component.css']
})
exportclassHelloComponent{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>
53
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
54
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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.tsfileandimplementabasicservicethatinitializesandmanagesthelistofcars.
//car.service.ts
import{Injectable}from'@angular/core';
import{Car}from'./car.model';
55
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
@Injectable({
providedIn:'root',
})
exportclassCarService{
privatecars:Car[]=[];
getCars():Car[]{
returnthis.cars;
}
addCar(car:Car):void{
this.cars.push(car);
56
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
}
}
3.CreateaCarComponent: Generateacomponenttodisplaythelistofcarsandallowuserstoaddnewcars.
Runthefollowingcommandintheterminal:
nggeneratecomponentcar-list
Openthegenerated car-list.component.ts
//car-list.component.ts fileandimplemen tthecomponentlogic.
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};
57
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
}
}
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()">
58
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
<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
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:
59
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Excersice-10:
ProblemStatement1:
CourseName:AngularJS
ModuleName:StructuralDirectives-ngIfCreatealoginformwithusernameand
passwordfields.Iftheuserentersthecorrectcredentials,itshouldrendera"Welcome
<>"messageotherwiseitshouldrender"InvalidLogin!!!Pleasetryagain..."message.
Openthe fileandimplementtheloginform:
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>Inthis
template:
Weusetwo-waydatabinding([(ngModel)])tobindtheinputfieldstothe
properties.
60
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
(ngSubmit) login()
username and password
61
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Theformhasa eventthatcallsthe method.
Weusethe ngIf
directivetoconditionallyrendereitherthewelcomemessageortheinvalidlogin
message.
//login.component.ts
import{Component}from'@angular/core';
62
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
@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
// Forsimplicity,we'llconsider it asuccessfulloginifbothfieldsare non-emptyif
(this.username&&this.password) {
this.isLoggedIn=true;
} else
{ this.isLoggedIn=fals
e;
}
}
}
Note:Inareal-worldscenario,youwouldperformactualauthentication,possiblywithaserviceorAPIcall.
//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],
})
63
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
exportclassAppModule{}
64
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
5.RuntheApplication:IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:
ngserve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheloginform.Tryentering
somecredentials,andyou'llseeeitherthewelcomemessageortheinvalidloginmessagebasedonthelogicin
the login()method.
Thisexampledemonstratestheuseofthe ngIfdirectivetoconditionallyrendercontentbasedonthelogin
status.
ProblemStatement2:
ModuleName:ngForCreateacoursesarrayandrenderingitinthetemplateusingngFordirectiveinalist
format.
Tocreateanarrayofcoursesandrenderitinthetemplateusingthefollowthesesteps: ngFordirective,
1.UpdateAppComponentTypeScript:Openthearrayof app.component.tsfileanddefinean
coursesinthe 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.htmlfileandusethe
. arrayandrenderitinalistformat:
ngFo directivetoiterateoverthe course
r s
<!-- .component.html-->
app ourses</h2>
<h2>
C
For="letcourseofcourses">{{cour se}}</ i>
<ul> l
<li*n
g
</ul>
65
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Inthistemplate,the and *ngFo directive isusedtoloopover each courseinthe coursesarray
r element.
renderitinsidean <li
>
66
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
67
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
ProblemStatement3:
ModuleName:ngSwitch
DisplaythecorrectoptionbasedonthevaluepassedtongSwitchdirective.
Openthe fileanddefineavariabletocontrolthe
1.UpdateAppComponentTypeScript: app.component.ts
switch:
//app.component.t
s
import{Component}from'@angular/core';
@Component({ sele
ctor:'app-root',
templateUrl:'./app.component.html'
,styleUrls:['./app.component.css'],
})
export class
AppComponent{ selectedOption:string='o
ption1';
}
<!--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>
68
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
<!--Changeoption-->
<div>
<label>Selectanoption:</label>
<select[(ngModel)]="selectedOption">
<optionvalue="option1">Option1</option>
<optionvalue="option2">Option2</option>
<optionvalue="option3">Option3</option>
</select>
</div>
69
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
Inthistemplate:
<div> selectedOption
The ngSwitch directiveisappliedtoa element,anditsvalueisboundtothe
variable.
Differentcasesaredefinedusingthe *ngSwitchCase directive,andadefaultcaseisdefinedusing
*ngSwitchDefault.
ThecontentinsideeachcaseisconditionallydisplayedbasedonthevalueofselectedOption.
A <select> elementisincludedtochangethevalueof selectedOption dynamically.
3.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
comman
d: ng
serve
Openyourwebbrowserandnavigatetohttp://
localhost:4200.YoushouldseetheoptionsdisplayedbasedontheinitialvalueofselectedOption.Changingthe
valueinthedropdownwillupdatethedisplayed option accordingly.
Thisexampledemonstrateshowtousethe ngSwitch
directivetoconditionallyrenderdifferentoptionsbased
on the value of a variablein Angular.
ProblemStatement4:
ModuleName:CustomStructuralDirectiveCreateacustomstructuraldirectivecalled
'repeat'whichshouldrepeat the elementgivenanumberoftimes.
1.CreatetheDirective: Runthefollowingcommandinyourterminaltogenerateanewdirective:
nggeneratedirectiverepeat
repeat.directive.ts fileandimplementthecustom
Open
th
2.Implement the RepeatDirective: e
RepeatDirective .Thisdirectivewilltakeanumberasaninputandrepeatthehostelementthatmanytimesin
theDOM.
//repeat.directive.ts
70
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
@Directive({ selector:'[a
ppRepeat]',
})
exportclassRepeatDirective{
71
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
constructor(
privatetemplateRef:TemplateRef<any>,private
viewContainer: ViewContainerRef
){}
@Input()set appRepeat(times:number){for(leti
=0;i<times;i++) {
this.viewContainer.createEmbeddedView(this.templateRef);
In thisdirective:
appRepeat is aninputproperty that takes the numberof times to repeat.
The
representsthecontentoftheelementthedirectiveisappliedto.
The TemplateRef
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>
72
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
//app.module.ts
import{BrowserModule}from'@angular/platform-
browser';import{ NgModule } from '@angular/core';
73
DepartmentofCSE(DS),PEC
MEANStackTechnologiesLabManual
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
timesasspecifiedbaypthpeRepeat directive.
DepartmentofCSE(DS),PEC