MST 6173 - Merged
MST 6173 - Merged
No:1
Page No.:
Date:
Experiment-1
1.aCourseName:AngularJS
ModuleName:Angular ApplicationSetup
Aim:Observethelink http://localhost:4200/welcomeonwhichthemCart applicationisrunning.Perform
thebelowactivitiestounderstandthefeaturesoftheapplication.
Description:
INSTALLINGANGULAR.JSINVISUALSTUDIO
InstalltheAngularCLI
Youcan use the Angular CLI to create projects,generate applicationand library code, and perform a
varietyofongoingdevelopmenttaskssuchastesting,bundling,anddeployment.
ToinstalltheAngularCLI,openaterminalwindowandrunthefollowingcommand:
npminstall-g@angular/cli
On Windows client computers, the execution of PowerShell scripts is disabled by default. To allow the
executionofPowerShellscripts,whichisneededfornpmglobalbinaries,youmustsetthe following execution
policy:
Set-ExecutionPolicy-ScopeCurrentUser-ExecutionPolicyRemoteSigned
Carefullyreadthemessagedisplayedafterexecutingthecommandandfollowtheinstructions.Makesure
youunderstandtheimplicationsofsettinganexecutionpolicy.
Createaworkspaceandinitialapplication
Youdevelopappsinthecontextofan Angularworkspace.
Tocreateanewworkspaceandinitialstarterapp:
1. RuntheCLIcommandngnewandprovidethenamemy-app,asshownhere:
content_copyng new my-app
2. Thengnewcommandpromptsyouforinformationaboutfeaturestoincludeintheinitialapp.Accept the
defaultsby pressing the Enter or Return key.
TheAngularCLIinstallsthenecessaryAngularnpmpackagesandotherdependencies.Thiscantakea few
minutes.
TheCLIcreatesanewworkspaceandasimpleWelcomeapp,readytorun.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
Runtheapplication
TheAngularCLIincludesaserver,foryoutobuildandserveyourapplocally.
1. Navigatetotheworkspacefolder,suchasmy-app.
2. Runthefollowingcommand:
my-app
ngserve--open
The ngserve commandlaunchesthe server,watchesyourfiles,andrebuildstheapp asyoumake changes to those
files.
The--open(orjust-o)optionautomaticallyopensyourbrowsertohttp://localhost:4200/.
Output:
PSC:\Users\SRK\Desktop\csebrockers>npminstall-g@angular/cli
PSC:\Users\SRK\Desktop\csebrockers>Set-ExecutionPolicy -ScopeCurrentUser-ExecutionPolicy
RemoteSigned
PSC:\Users\SRK\Desktop\csebrockers>ngnewmy-app
Node.js version v19.8.1 detected.
OddnumberedNode.jsversionswillnotenterLTSstatusandshouldnotbeusedforproduction.Formore
information,pleaseseehttps://nodejs.org/en/about/releases/.
?Wouldyouliketo addAngularrouting?Yes
?Whichstylesheetformatwouldyouliketouse?Less[http://lesscss.org] CREATE
my-app/angular.json (2874 bytes)
CREATE my-app/package.json (1037 bytes)
CREATE my-app/README.md (1059 bytes)
CREATE my-app/tsconfig.json (901 bytes)
CREATE my-app/.editorconfig (274 bytes)
CREATE my-app/.gitignore (548 bytes)
CREATEmy-app/tsconfig.app.json(263bytes)
CREATEmy-app/tsconfig.spec.json(273bytes)
CREATE my-app/.vscode/extensions.json (130 bytes)
CREATE my-app/.vscode/launch.json (470 bytes)
CREATE my-app/.vscode/tasks.json (938 bytes)
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
CREATE my-app/src/favicon.ico (948 bytes)
CREATE my-app/src/index.html (291 bytes)
CREATE my-app/src/styles.less (80 bytes)
CREATEmy-app/src/app/app-routing.module.ts (245 bytes)
CREATE my-app/src/app/app.module.ts (393 bytes)
CREATE my-app/src/app/app.component.html (23115 bytes)
CREATEmy-app/src/app/app.component.spec.ts(991bytes)
CREATE my-app/src/app/app.component.ts (211 bytes)
CREATE my-app/src/app/app.component.less (0 bytes)
CREATE my-app/src/assets/.gitkeep (0 bytes)
✔Packagesinstalledsuccessfully.
Directoryisalreadyunderversioncontrol.Skippinginitializationofgit.
PSC:\Users\SRK\Desktop\csebrockers>cdmy-app
>>ngserve--open
Node.jsversionv19.8.1detected.
OddnumberedNode.jsversionswillnotenterLTSstatusandshouldnotbeusedforproduction.Formore
information,pleaseseehttps://nodejs.org/en/about/releases/.
?WouldyouliketosharepseudonymoususagedataaboutthisprojectwiththeAngularTeam
atGoogleunderGoogle'sPrivacyPolicyathttps://policies.google.com/privacy.Formore
detailsandhowtochangethissetting,seehttps://angular.io/analytics.Yes
Thankyouforsharingpseudonymoususagedata.Shouldyouchangeyourmind,thefollowing command will
disable this feature entirely:
ng analytics disable
Globalsetting:enabled
Local setting: enabled
Effectivestatus:enabled
✔Browserapplicationbundlegenerationcomplete.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
styles.css, styles.js | styles |230.67kB|
main.js | main |48.08 kB |
runtime.js | runtime |6.51 kB |
|InitialTotal|2.89MB
Buildat:2023-07-24T04:42:02.409Z-Hash:8542936140e45a51-Time:7980ms
**AngularLiveDevelopmentServerislisteningonlocalhost:4200,openyourbrowseron http://localhost:4200/
**
√Compiledsuccessfully.
1b.CourseName:AngularJS
ModuleName:ComponentsandModules
Aim:CreateanewcomponentcalledhelloandrenderHelloAngularonthepage.
Description:
Step1-Testthedefaultapp
Inthisstep,afteryoudownloadthedefaultstartingapp,youbuildthedefaultAngularapp.Thisconfirms
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
thatyourdevelopmentenvironmenthaswhatyouneedtocontinuethetutorial. In the
Terminal pane of your IDE:
1. Inyourprojectdirectory,navigatetothefirst-appdirectory.
2. Runthiscommandtoinstallthedependenciesneededtoruntheapp. npm
install
3. Runthiscommandtobuildandservethedefaultapp. ng
serve
Theappshouldbuildwithouterrors.
4. Inawebbrowseronyourdevelopmentcomputer,openhttp://localhost:4200.
5. Confirmthatthedefaultwebsiteappearsinthebrowser.
6. Youcanleavengserverunningasyoucompletethenextsteps.
Step2-Reviewthefilesintheproject
Inthisstep,yougettoknowthefilesthatmakeupadefaultAngularapp. In the
Explorer pane of your IDE:
1. Inyourprojectdirectory,navigatetothefirst-appdirectory.
Openthesrcdirectory toseethesefiles.
Inthefileexplorer,findthe Angularappfiles (/src).
index.htmlistheapp'stoplevelHTMLtemplate.
style.cssistheapp'stoplevelstylesheet.
main.tsiswheretheappstartrunning.
favicon.icoistheapp'sicon,justasyouwouldfindinanywebsite.
Inthefileexplorer,findtheAngularapp'scomponentfiles(/app).
app.component.tsisthesourcefilethatdescribestheapp-rootcomponent. Thisisthetop-level Angular
componentintheapp. A componentisthebasicbuildingblockof an Angularapplication. The
component
descriptionincludes thecomponent'scode,HTML template,andstyles,whichcan bedescribedin this file,
orinseparatefiles.
In thisapp, thestyles are in aseparatefilewhilethecomponent's codeand HTMLtemplate arein this file.
app.component.cssisthestylesheetforthiscomponent.
Newcomponentsareaddedtothisdirectory.
Inthefileexplorer,findtheimagedirectory(/assets)thatcontainsimagesusedbytheapp.
Inthe fileexplorer,findthefiles and directoriesthatan Angular appneeds tobuild and run, but they are
not files thatyou normally interactwith.
.angularhasfilesrequiredtobuildtheAngularapp.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
.e2ehasfilesusedtotesttheapp.
.node_moduleshasthenode.jspackagesthattheappuses.
angular.jsondescribestheAngularapptotheappbuildingtools.
package.jsonisusedbynpm(thenodepackagemanager)torunthefinishedapp.
tsconfig.* are the files that describe the app's configuration to the Typescript compiler.
After you have reviewed the files that make up anAngular app project, continue to the next step.
Step 3 - Create Hello World
In this step, you update the Angular project files tochange the displayedcontent.
In your IDE:
1. Openfirst-app/src/index.html.
2. Inindex.html,replacethe<title>elementwiththiscodetoupdatethetitleoftheapp. Replace
in src/index.html
<title>Homes</title>
Then,save thechangesyoujustmade toindex.html.
3. Next,openfirst-app/src/app/app.component.ts.
4. Inapp.component.ts,inthe@Componentdefinition, replacethetemplatelinewiththiscodeto change
the text in the app component.
Replace in src/app/app.component.ts
template:`<h1>Hello world!</h1>`,
5. 5. In app.component.ts, intheAppComponentclass definition, replace the title linewith this code
to change the component title.
Replaceinsrc/app/app.component.ts
title = 'homes';
Then,savethechangesyoumadeto app.component.ts.
6. Ifyoustoppedthengservecommandfromstep1,intheTerminalwindowofyourIDE,runng serve
again.
7. Openyourbrowserandnavigate tolocalhost:4200 andconfirmthattheappbuildswithouterrorand
DisplaysHelloworldinthe titleandbodyofyourapp:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
Program:
Helloworld.js
Index.html:
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<title>Default</title>
<basehref="/">
<metaname="viewport"content="width=device-width,initial-scale=1">
<linkrel="icon"type="image/x-icon"href="favicon.ico">
<linkrel="preconnect"href="https://fonts.googleapis.com">
<linkrel="preconnect"href="https://fonts.gstatic.com"crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:ital,wght@0,400;0,700;1,400;1
,700&display=swap"rel="stylesheet">
</head>
<body>
<app-root></app-root>
</body>
</html>
Main.ts:
import { bootstrapApplication,provideProtractorTestingSupport}from '@angular/platform-browser';
import{AppComponent}from'./app/AppComponent';
bootstrapApplication(AppComponent, {providers:[provideProtractorTestingSupport()]})
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
.catch(err=>console.error(err));
Style.css:
{
margin:0;
padding:0;
}
body{
font-family:'BeVietnamPro',sans-serif;
}
:root{
--primary-color:#605DC8;
--secondary-color:#8B89E6;
--accent-color:#e8e7fa;
--shadow-color:#E8E8E8;
}
button.primary{
padding:10px;
border:solid1px var(--primary-color);
background: var(--primary-color);
color: white;
border-radius:8px;
}
App.component.css
:host {
--content-padding:10px;
}
header {
display:block;
height: 60px;
padding:var(--content-padding);
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
box-shadow:0px5px25pxvar(--shadow-color);
}
.content{
padding:var(--content-padding);
}
App.component.ts
import{Component}from'@angular/core';
@Component({
selector:'app-root',
standalone: true,
imports: [],
template: `<h1>Hello</h1>`,
styleUrls:['./app.component.css'],
})
exportclassAppComponent{
title = 'default';
}
Output:
~/projects/qqsjdl--run
> npminstall--legacy-peer-deps&&npmstart
npmWARNdeprecateduuid@3.4.0:Pleaseupgradetoversion7orhigher.Olderversionsmayuse Math.random()
in certain circumstances, which is known to be problematic. See
https://v8.dev/blog/mathrandomfordetails.
npmWARNdeprecatedhar-validator@5.1.5:thislibraryisnolongersupported npm
WARN deprecatedrequest@2.88.2: requesthas been deprecated, see
https://github.com/request/request/issues/3142
npmWARNdeprecatedprotractor@7.0.0:Wehavenewstoshare-Protractorisdeprecated andwill reach
end-of-lifeby Summer2023.To learn moreandfindoutaboutotheroptionspleaserefer to thispost on
theAngularblog.ThankyouforusingandcontributingtoProtractor.https://goo.gle/state-of-e2e-in
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
angular added 1062 packages in 10s
104packagesarelookingforfunding
run `npm fund` for details
> angular.io-example@0.0.0start
> ngserve
✔Browserapplicationbundlegenerationcomplete.
✔Compiledsuccessfully.
✔Browserapplicationbundlegenerationcomplete. 5
unchanged chunks
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
Aim:Addaneventtothehellocomponenttemplateandwhenitisclicked,itshouldchangethe
courseName.
Description:
ToaddaneventtoanAngularcomponent, you:
1. Define theeventintheHTMLtemplateusingparentheses,like(click)forabuttonclick.
2. Createamethodinthecomponent'sTypescriptsfiletohandletheevent.Forexample,aclickevent would
call a method like onClick().
3. Passdataifneededfromthetemplatetotheeventhandlerbyincludingvaluesinsidetheevent (e.g., passing
text or numbers).
Additionally,ifyouneedtocommunicatebetweencomponents,likesendinganeventfromachildtoa
parentcomponent,AngularprovidesEventEmitter.Thisallowsthechildcomponenttoemitanevent,
whichtheparentcomponentcanlistentoandhandleaccordingly.
Program:
hello.component.ts:
import{Component,OnInit}from'@angular/core';
@Component({
selector:'app-hello',
templateUrl:"./hello.component.html",
styleUrls: ['./hello.component.css']
})
exportclassHelloComponentimplementsOnInit{
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
courseName="MSD";
constructor() { }
ngOnInit() {
changeName() {
this.courseName="CSE";
hello.component.html:
<h1>Welcome</h1>
<h2>CourseName:{{courseName}}</h2>
<button><p(click)="changeName()">Clickheretochange</p></button>
hello.component.css:
p{
color:rgb(255,60,0);
font-size:20px;
Output:
PSC:\Users\CSE\Desktop\angular\MyApp\src\app>ngserve--open--port3000
✔Browserapplicationbundlegenerationcomplete.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
styles.css, styles.js | styles |230.44kB|
|InitialTotal|2.85MB
√Compiledsuccessfully.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
1.d Course Name: Angular JS
ModuleName:ChangeDetection
Aim:ProgressivelybuildingthePoolCarzapplication.
Description:
1. BuildingthePoolCarzapplicationinAngularwouldinvolveprogressivelycreatingdifferent features and
functionalities step by step.
2. SettingUptheProject:YouwouldstartbysettingupanAngularprojectusingAngularCLI, whichprovides
aneasyway to create andmanage Angular applications. This includesdefiningthe
rootmodule,installingnecessarydependencies,andcreatingthemaincomponent.
3. Routing: You'llsetup Angular’s routing tonavigatebetweendifferentviews,such as ahomepage, car
details, or booking page. This involves defining routes in the app’s routing module and linkingthem to
components.
4. Services for Data Handling: You would create Angular services tohandle data logic,such asfetching a
list of cars, booking details, and car availability. Services act as a bridge between the
componentandthebackend(likeaRESTAPI)tofetchorsenddata.
5. FormsforUserInput:Forbookingacar,you’dneedforms.Angularprovidestwotypesof forms:Template-
drivenformsandReactiveforms.Forhandlingthebookingprocess,you’d typically
usereactiveformstocaptureandvalidateuserinputslikecarselection,date,anduser details.
6. HTTP Requests: To communicate with a backend server (for car listings, booking data, etc.), you
would use Angular’s HttpClientModule to send GET, POST, PUT, and DELETE requests to
theserver.Thisallowstheapptofetchdataorsubmituseractionslikebookingacar.
7. StylingtheApplication:Asyoubuildoutthecomponents,you’llapplystylesusingeitherplain
CSS,SCSS,orCSSframeworkslikeBootstraporAngularMaterialforapolished,responsive design.
Change detection is the process through which Angular checks to see whether your application state has
changed,andifanyDOMneedstobeupdated.Atahighlevel,Angularwalksyourcomponentsfromtop
tobottom,lookingforchanges.Angularrunsitschangedetectionmechanismperiodicallysothatchanges
tothedatamodelarereflectedinanapplication’sview.Changedetectioncanbetriggeredeithermanually or through an
asynchronous event (for example, a user interaction or an XMLHttpRequest
completion).Changedetectionishighlyoptimizedandperformant,butitcanstillcauseslowdownsiftheapplication
runs it too frequently.
Inthisguide,you’lllearnhowtocontrolandoptimizethechangedetectionmechanismbyskippingparts of your
application and running change detection only when necessary. The Angular change detection
mechanismismuchmoretransparentandeasierto reasonaboutthanits equivalentin AngularJs.Butthere
arestillsituations(likewhendoingperformanceoptimizations)whenwe reallyneedtoknowwhat'sgoing on under the
hood.
Overridingbrowserdefaultmechanisms
WhathappensisthatAngularatstart-uptimewillpatchseverallow-levelbrowserAPIs,suchasfor
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
exampleaddEventListener,whichisthebrowserfunctionusedtoregisterallbrowserevents,including
clickhandlers.AngularwillreplaceaddEventListenerwithanewversionthatdoestheequivalentofthis:
// this is the new version of addEventListener
function addEventListener(eventName, callback) {
callRealAddEventListener(eventName,function(){
callback(...);
var changed = angular.runChangeDetection();
if (changed) {
angular.reRenderUIPart();
}
});
}
Thechangedetectiontree
@Component({
selector:'todo-item',
{{todo.description}}
-completed:{{todo.completed}}</span>`
})
exportclassTodoItem{
@Input()
todo:Todo;
EachAngularcomponenthasanassociatedchangedetector,whichiscreatedatapplicationstartuptime.
For
example,takethefollowing
TodoItem component:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:1
Page No.:
Date:
Program:
Index.html:
<!Doctypehtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<title>PoolCarz</title>
<basehref="/">
<metaname="viewport"content="width=device-width,initial-scale=1">
<a href="https://m.media-amazon.com/images/I/51hoKtF9B2L.jpg">LOKESH</a>
</head>
<body>
<app-root></app-root>
</body>
</html>
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
EXPERIMENT-2
2(a)CourseName:AngularJS
ModuleName:StructuralDirectives–ngIf
Description: The ngIf directive in Angular is a powerful structural directive used to conditionally
includeorexcludeanHTMLelementfromtheDOMbasedonthetruthinessofanexpression.Whenthe
expressionevaluatestotrue,theassociatedelementisaddedtotheDOM. Iftheexpressionevaluatesto false, the
element is removed.
Thisdirectiveisoftenusedtoshoworhideelementsbasedondynamicconditions.It'scommonlyusedin
scenarios such asdisplayingcontent conditionally, rendering components based on userpermissions, or
toggling visibility of UI elements.
HowngIfWorks:
WhenAngularevaluatestheconditiontiedtongIf,itcheckswhethertheexpressionresultsintrueor false:
Iftrue:TheassociatedHTMLelementisrendered.
Iffalse:TheassociatedHTMLelementisremovedfromtheDOM.
Thismeansthatifacomponent,element,ortemplatelinkedwithngIfisnotintheDOM,Angularwillnot process
anyevent bindings or apply styles or animations to it, making itmore efficientin termsof resource
management.
1. ConditionalRendering:Itallowsyoutoconditionallyincludeorexcludeelementsorcomponents from
the DOM.
2. MemoryEfficiency:ByremovingelementsfromtheDOM,ngIfconservesmemoryresources,
unlike ngClass or ngStyle which only hide the element but leave it in the DOM.
3. DynamicUpdates:WhentheexpressiontiedtongIfchanges,Angularautomaticallyupdatesthe
DOM by either adding or removing the element.
BasicSyntax:
<div*ngIf="condition">Contentgoes here</div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
Program:
App.component.html
<div*ngIf="!submitted">
<form>
<label>UserName</label>
<inputtype="text"#username/><br/><br/>
<labelfor="password">Password</label>
<inputtype="password"name="password" #password/><br/>
</form>
<button(click)="onSubmit(username.value,password.value)">Login</button>
</div>
<div*ngIf="submitted">
<div*ngIf="isAuthenticated;elsefailureMsg">
<h4>Welcome{{userName}}</h4>
</div>
<ng-template#failureMsg>
<h4>InvalidLogin!!!Pleasetryagain...</h4>
</ng-template>
<buttontype="button"(click)="submitted=false">Back</button>
</div>
App.component.ts
import{Component}from'@angular/core';
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css'],
})
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
exportclassAppComponent{
isAuthenticated!: boolean;
submitted = false;
userName!: string;-
onSubmit(name:string,password:string){ this.submitted
= true;
this.userName=name;
if(name==='admin'&&password==='admin'){
this.isAuthenticated = true;
} else
{this.isAuthenticated=false
;
}
}
}
App.module.ts
import{NgModule}from'@angular/core';
import{BrowserModule }from'@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import{HttpClientModule}from'@angular/common/http';
import { AppComponent } from './app.component';
import{AuthorsComponent}from'./authors.component';
@NgModule({
imports:[BrowserModule,FormsModule,
HttpClientModule],
declarations:[AppComponent,AuthorsComponent],
bootstrap: [AppComponent]
})
exportclassAppModule{}
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
index.html
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<title>HelloWorld</title>
<basehref="/">
<metaname="viewport"content="width=device-width,initial-scale=1">
<linkrel="icon"type="image/x-icon"href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
2(b)CourseName:AngularJS
Module Name: ngFor
Aim:CreateacoursesarrayandrenderingitinthetemplateusingngFordirectiveinalistformat.
Step1:DefinetheCoursesArrayintheComponent
InyourAngularcomponent,youfirstneedtocreateanarraycalledcourses.Eachiteminthearraycan represent a
course, which might include properties like id, title, description, etc.
Step2:UsethengForDirectivetoRendertheListintheTemplate
Inthecorrespondingtemplate(HTML),youwillusethe*ngFordirectivetoloopoverthecoursesarray and
display each course item in a list format.
Step3:RuntheApplication
Onceyou’vesetupthecomponentwiththecoursesarrayandthengFordirectiveinthetemplate,the Angular
framework will automatically update the DOM and render the courses as a list.
Program:
App.component.ts
import{Component}from'@angular/core';
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponent{
courses: any[] = [
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
{id:1,name:'TypeScript'},
{id:2,name:'Angular'},
{id:3,name:'NodeJS'},
{id:1,name:'TypeScript'}
];
App.component.html
<ul>
<li*ngFor="letcourseofcourses;leti=index">
{{i}}-{{course.name}}
</li>
</ul>Index.htm
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="utf-8">
<title>HelloWorld</title>
<basehref="/">
<metaname="viewport"content="width=device-width,initial-scale=1">
<linkrel="icon"type="image/x-icon"href="favicon.ico">
</head>
<body>
<app-root></app-root>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
</body>
</html>
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
2(c)CourseName:AngularJS
Module Name: ngSwitch
Aim:CourseName:AngularJSModuleName:ngSwitchDisplaythecorrectoptionbasedonthevalue passed to
ngSwitch directive.
Description:InAngular,thengSwitchdirectiveisusedtoconditionallydisplayelementsbasedonan
expression or variable. You specify an expression (the ngSwitch value) on a parent container and then
definemultiplengSwitchCasedirectivesforeachpossiblevalue.Iftheexpressionmatchesthevalueofa
ngSwitchCase,thatcase’scontentisdisplayed.Optionally, youcanalsouseangSwitchDefaultdirective to
specify the default case when no match is found.
Step1:DefinetheValueintheComponent
Step2:SetUpthengSwitchandngSwitchCaseintheTemplate
Step3:ChangingtheValue
YoucanchangethevalueofselectedLanguagedynamically,suchasthroughauserinteraction,and Angular
will automatically update the DOM to display the corresponding case.
Program:
App.component.ts
import{Component}from'@angular/core';
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponent{
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
choice = 0;
nextChoice(){
this.choice++;
App.component.html
<h4>
Currentchoiceis{{choice}}
</h4>
<div[ngSwitch]="choice">
<p*ngSwitchCase="1">FirstChoice</p>
<p*ngSwitchCase="2">SecondChoice</p>
<p*ngSwitchCase="3">Third Choice</p>
<p*ngSwitchCase="2">SecondChoiceAgain</p>
<p*ngSwitchDefault>Default Choice</p>
</div>
<div>
<button(click)="nextChoice()">
Next Choice
</button>
</div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
2(d)CourseName:AngularJS
ModuleName:CustomStructuralDirective
Aim:Createacustomstructuraldirectivecalled'repeat'whichshouldrepeattheelementgivenanumber of
times.
Description:In Angular, you can create custom structural directives to control how elements are
displayed in the DOM. A structural directive manipulates the layout byadding or removing elements. In
thiscase,we’llcreateacustomstructuraldirectivecalledrepeat,whichrepeatsanelementagivennumber of times
based on an input value.
Step-by-StepImplementation:
Step1:GeneratetheCustomDirective
StartbygeneratingacustomdirectiveusingAngularCLI:
Step2:Implementthe repeatDirectiveLogic
Opentherepeat.directive.tsfileandmodifyittorepeatanelementthespecifiednumberoftimes
Step3:UsetherepeatDirectiveintheTemplate
Aftercreatingthedirective,youcanuseitinyourAngularcomponentstorepeatanelementmultiple times.
Here's an example of how to use the appRepeat directive in a template.
Step4:AddtheDirectivetotheModule
EnsurethattheRepeatDirectiveisdeclaredinyourmodulesoitcanbeusedthroughoutyourapplication. This is
typically done in the app.module.ts fill.
Step5:TesttheDirective
RunyourAngularapplicationandseehowtheappRepeatdirectiveworks.Ifyoupassanumberlike5,the content
inside the <div> should be repeated 5 times.
Program:
App.module.ts
import{BrowserModule }from'@angular/platform-browser';
import{AppComponent}from'./app.component';
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
import{RepeatDirective}from'./repeat.directive';
@NgModule({
declarations: [
AppComponent,
RepeatDirective
],
imports: [
BrowserModule
],
providers:[],
bootstrap:[AppComponent]
})
exportclassAppModule{}
repeat.directive.ts
@Directive({
selector:'[appRepeat]'
})
exportclassRepeatDirective{
this.viewContainer.createEmbeddedView(this.templateRef);
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:2
PageNo.:
Date:
}
App.component.html
<h3>StructuralDirective</h3>
<p*appRepeat="5">Iambeingrepeated...</p>
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:3
PageNo:
Date:
Experiment-3
3a)CourseName: AngularJS
ModuleName:AttributeDirectives– ngStyle
Aim:ApplymultipleCSSpropertiestoaparagraphina componentusingngStyle.
ngStylebindsanobjecttoanelementandappliesthe specifiedstylesdynamically.
The keys in the paragraphStyles object correspond to the CSS propertynames (using
camelCase notation for hyphenated CSS properties, like background-color becomes
backgroundColor).
Youcanaddasmanystylesasneededtotheobject.
Program:
App.component.html
<p[ngStyle]="{color:colorName,
'font-weight':fontWeight,borderBottom:borderStyle}">
Demo for attribute directive ngStyle
</p>
App.component.ts
import{Component}from'@angular/core';
@Component({ selector: 'app-root',
templateUrl:'./app.component.html',styleUrls: ['./app.component.css']
})
App.component.css
p{font-family:Lato;}
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:3
PageNo:
Date:
App.module.ts
import{ NgModule}from'@angular/core';
imports:[BrowserModule,FormsModule,
HttpClientModule],
declarations:
[AppComponent,AuthorsComponent],
bootstrap:
[AppComponent]})
exportclassAppModule{}
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 22 AA 99 11 AA 66 11 77 33
2
Expt.No:3
PageNo:
Date:
3b)CourseName:AngularJS
Module Name: ngClass
Aim:ApplymultipleCSSclassesto thetextusingngClassdirective.
Description: ToapplymultipleCSS classes toanelementusingthe ngClass directive inAngular, you
can bind the ngClass directive to an object, array, or string containing the class names you want to
apply.
Step1:UsinganObject
Youcanuseanobject where thekeys are class namesand the values arebooleanexpressions. Ifthe value
is true, the class will be applied; if false, it will not.
'text-primary':trueappliesthetext-primaryclass.
'bg-light':trueappliesthebg-lightclass.
'font-bold':falsedoes notapplythefont-boldclassbecauseitsvalueisfalse.
Step2:UsinganArray:
Step3:UsingaString:
Youcanalsobindasinglestringwithspace-separated classnames.
This directlyappliesthethreeclassestotheparagraph.
Program:
App.component.css
.bordered{
border:1pxdashedblack;background-color:#eee;
.color{
color:blue;
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:3
PageNo:
Date:
App.component.html
<div[ngClass]="{bordered:isBordered,color:isColor}">Border{{isBordered?"ON":"OFF"
}}
</div>
App.component.ts
exportclassAppComponent{ isBordered
= true;
isColor=true;
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:3
PageNo:
Date:
3c)CourseName:AngularJS
ModuleName:Custom AttributeDirective
Aim: Createanattribute directive called 'showMessage'whichshould displaythe given message in a
paragraph when a user clicks on it and should change the text color to red.
Description: TocreateanAngularattributedirective called showMessage, whichdisplays a given
message in a paragraph when a user clicks on it and changes the text color to red, follow these
steps:
Step1:Createthederivative
InAngular,directivesare used tomanipulate DOMelements.Youcancreate anattribute directive by
generating it with Angular CLI or manually.
Step2.DirectiveCode
Editthegeneratedshow-message.directive.tsfiletoimplementthedesiredbehavior.
Step3.ExplanationoftheCode:
Program-:
App.component.ts
import {Component }from'@angular/core';@Component({
selector: 'app-root',
templateUrl:'./app.component.html',styleUrls: ['./app.component.css']
})
exportclassAppComponent{
myMessage='Hello,I am fromattributedirective';
}
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:3
PageNo:
Date:
}}
App.component.html
<h3>AttributeDirective</h3>
<p[appMessage]="myMessage">ClickHere</p>
App.component.css
h3 {
color:#369;
font-family:Arial,Helvetica,sans-serif;font-size:250%;
}
p{
color:#ff0080;
font-family:Arial,Helvetica,sans-serif;font-size:150%;
}
App.component.ts
import {Component }from'@angular/core';@Component({
selector: 'app-root',
templateUrl:'./app.component.html',styleUrls: ['./app.component.css']
})
exportclass AppComponent{
myMessage='Hello,Iamfromattributedirective';
}
Output
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
Experiment-4
4a) Course Name: Angular JS
ModuleName:PropertyBinding
Aim:Bindingimagewithclasspropertyusingpropertybinding.
Description: Property Binding is a one-way data-binding technique. In property binding, we bind a
property of a DOM element to a field which is a defined property in our component TypeScript code.
Actually, Angular internally converts string interpolation into property binding. In this, we bind the
property of a defined element to an HTML DOM element. To bind to an element's property, enclose it in
square brackets, [], which identifies the property as a target property.A target property is the DOM
property to which you want to assign a value.
Syntax:
<element[property]='typescript_property'>
Example:<imgng-src="{{imageUrl}}"alt="Image">
Here,theng-srcattributebindstheimageUrldatafromtheAngularJScontrollertothesrcpropertyofthe image
element.
ImageRepresentationofPropertyBindingProcess:
HereisaconceptualflowthatshowsthestepsofpropertybindinginAngularJS:
1. ControllerSetup→Data(imageUrl)isdefinedinthecontroller.
2. BindingExpressioninHTML→HTMLelementusesng-src="{{imageUrl}}"tobinddata.
3. AngularJSCompilation→AngularJSevaluatesandprocessesthebinding.
4. ViewUpdate→Dataisdynamicallyreflectedintheview(imageisdisplayed).
Thisimagewillshowtheflowfromthecontrollertotheviewwiththedatabindinginaction.
Program:
//App.components.ts:
import{ PropertyComponent } from './property/property.component';
@Component({
selector:'app-root',
imports:[RouterOutlet,PropertyComponent],
template: `<div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 5 8
Expt.No:4
PageNo:
Date:
<img[src]="'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQkKjoRPK-Mr02nVT-
mRsRYaRWQ6-KAi1O06w&s'" />
</div>`,
styleUrls: ['./app.component.css']
})
//propertycomponent.html
<p>propertyworks!</p>
<img[src]="'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQkKjoRPK-Mr02nVT-
mRsRYaRWQ6-KAi1O06w&s'" />
//propertycomponent.ts
exportclassPropertyComponent{
imageUrl: string = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQkKjoRPK-Mr02nVT-
mRsRYaRWQ6-KAi1O06w&s';
}
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
Aim:Bindingcolspanattributeofatableelementtotheclassproperty.
Description: In AngularJS, attribute binding is a process used to bind dynamic data to an HTML
element's attribute. Unlike property binding, which deals directly with properties of DOM elements,
attribute binding allows you to manipulate the actual HTML attributes like title, class, or id.
WhatisAttributeBinding?
Withattributebinding,youcanbindvaluestoHTMLattributesofelements,suchassettingtheclass,id, href, or
even custom attributes based on the scope variable or model in AngularJS.
InAngularJS,thiscanbeachievedusingtheng-attr-*directive.
SyntaxforAttributeBinding:
<ang-attr-href="{{dynamicLink}}">Clickhere</a>
Inthisexample,theng-attr-hrefdirectiveisusedtobindthehrefattributeofthelinktothe
dynamicLink variable from the controller.
HereisaconceptualflowthatshowsthestepsofattributebindinginAngularJS:
1. ControllerSetup→Data(dynamicLink)isdefinedinthecontroller.
2. BindingExpressioninHTML→HTMLelementusesng-attr-href="{{dynamicLink}}"tobind the
data to the attribute.
3. AngularJSCompilation→AngularJSevaluatesandprocessesthebindingexpression.
4. ViewUpdate→TheattributeisdynamicallyreflectedintheHTMLelement(e.g.,<a
href="https://example.com">Click here</a>).
Program:
//App.component.ts
import{HelloComponent }from '../hello/hello.component';
@Component({
selector:'app-root',
imports:[HelloComponent],
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
template:'<app-hello></app-hello>',
styleUrls: ['./app.component.css']
})
exportclassAppComponent{
}
//hello.component.html
<tableborder="1">
<tr>
<td[attr.colspan]="colspanValue">First</td>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
<td>Fourth</td>
<td>Fifth</td>
</tr>
</table>
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
4c)CourseName:AngularJS
ModuleName:StyleandEventBinding
Aim:Bindinganelementusinginlinestyleanduseractionslikeenteringtextininputfields.
Description: Style binding allows you to bind dynamic data to the inline styles of an HTML element.
This makes it possible to change the appearance of elements based on the data in your AngularJS
controller.
WhatisStyleBinding?
Syntax:[style.styleproperty]
StepsInvolvedinStyleBinding:
1. ControllerSetup:
o Thecontrollerdefinesvariables(backgroundColorandfontSize)whichholdvaluesfor CSS
properties.
2. BindinginHTML:
o Theng-styledirectiveintheHTMLtemplatebindsthestylestothesecontrollervariables.
o Inthetemplate,wheneverthevalueof$scope.backgroundColoror$scope.fontSizechanges, the
styles of the <div> are automatically updated.
3. UserInteraction:
o Theuserclicksthebutton,triggeringthechangeStylefunctioninthecontroller.
o This updates the values of $scope.backgroundColor and $scope.fontSize, which
automatically updates the styles applied to the <div>.
2. EventBindinginAngularJS
Event binding in AngularJS allows you to bind actions (such as clicks, mouse events, keyboard events,
etc.) to AngularJS functions in the controller. This means that whenever the user triggers an event,
AngularJS executes a specified function.
WhatisEventBinding?
Event binding is used to capture user interactions (such as mouse clicks or key presses) and trigger
functions on the AngularJS controller in response to these interactions. You can use ng-click, ng-change,
and other event directives to bind events to specific functions.In AngularJS, the ng-click directive is
commonly used for event binding.
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
Syntax:(event)="method()"
StepsInvolvedinEventBinding:
1. ControllerSetup:
o Thecontrollerdefinesthevariablemessage,whichwillbedisplayedintheview.
2. BindinginHTML:
o Theng-clickdirectivebindsthechangeMessagefunctiontothebutton'sclickevent.
o Whenever thebuttonisclicked,thechangeMessage functioniscalled,andthemessage value is
updated.
3. UserInteraction:
o Whentheuserclicksthebutton,AngularJScapturestheclickeventandtriggersthe
changeMessage function, which updates the message displayed on the screen.
StyleBinding(ng-style)allowsyoutodynamicallyapplyCSSstylesbasedonAngularJS
controller data.
EventBinding(ng-click,ng-change,etc.)allowsyoutohandleuserinteractionsbytriggering
AngularJS functions in response to events like clicks or changes.
Program:
//app.component.html
<h1>Welcometo MyApp!</h1>
<p [style.color]="textColor"
[style.fontSize.px]="fontSize">This text color changes
dynamically!
</p>
<button(click)="changeColor()">ChangeColor</button>
//app.component.ts
import{Component}from'@angular/core';
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponent{ title
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
= 'app';
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
textColor='red';
fontSize = 16;
changeColor(){
this.textColor=this.textColor==='red'?'green':'red';
}
}
Output:
//app-component.html
<h1>EventBindingExample</h1>
<button(click)="onButtonClick()">ClickMe!</button>
<p>{{message}}</p>
<inputtype="text"(input)="onInputChange($event)"placeholder="Typesomething..."/>
//app-component.ts
import{Component}from'@angular/core';
@Component({
selector:'app-root',
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:4
PageNo:
Date:
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponent{
message: string = '';
onButtonClick() {
this.message='Buttonwasclicked!';//Updatemessagewhenbuttonisclicked
}
onInputChange(event:Event){
constinputElement=event.targetasHTMLInputElement; this.message
= `Input changed: ${inputElement.value}`;
}
}
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:
PageNo.:
Date:
Experiment-5
5a)CourseName:AngularJS
ModuleName:BuiltinPipes
Aim: Display the product code in lowercase and product name in uppercase using built-in pipes.
Description: The course"AngularJS" underthe module"Built-in Pipes" aimsto demonstrate how to
use Angular's built-in pipes to transformand display data in a specific format.
Inthismodule,theobjectiveisto:
Displaytheproductcodeinlowercase.
Displaytheproductnameinuppercase.
Toachievethis, Angular providesthe lowercase and uppercase pipes,whichare used to modify the
case of text directly in the HTML template.
Exampleofhowtousethesepipes:
<!--Displayproductcodeinlowercase-->
<p>{{productCode|lowercase}}</p>
<!--Displayproductnameinuppercase-->
<p>{{productName|uppercase}}</p>
Program:
App.component.ts
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 5 8
Expt. No:
PageNo.:
Date:
})
exportclassAppComponent{
productCode='PROD_P001';
productName = 'Laptop';
App.component.html
<h3>{{title|titlecase}}</h3>
<tablestyle="text-align:left">
<tr>
<th>ProductCode</th>
<td> {{productCode|lowercase}}</td>
</tr><tr>
<th>ProductName</th>
<td>{{productName|uppercase}}</td>
</tr></table>
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:
PageNo.:
Date:
5b)CourseName:AngularJS
ModuleName:PassingParameterstoPipes
Aim:Applybuilt-inpipeswithparameterstodisplayproductdetails.
Description:
PassingParameterstoPipesinAngularJS
Objective:
Learn how to apply built-inAngular pipes with parameters to formatand display product details
dynamically.
KeyTopics:
UnderstandingPipesin AngularJS
Pipesareusedfortransformingdataintemplates(e.g.,formattingdates,currency,ortext).
CommonBuilt-inPipeswithParameters:
currencyPipe:Formatsanumberascurrency.
{{product.price|currency:'USD':'symbol':'1.2-2'}}
datePipe:Formatsdatevalueswithdifferentformats.
{{product.releaseDate|date:'longDate'}}
slicePipe:Extractsaportionofanarrayorstring.
{{product.description|slice:0:50}}
numberPipe:Formatsnumberswith decimalprecision.
{{product.rating|number:'1.1-2'}}
ApplyingPipesinProductDetailsDisplay:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:
PageNo.:
Date:
<p>Rating:{{product.rating|number:'1.1-2'}}</p>
</div>
Program:
App.component.ts
import {Component }from'@angular/core';
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponent{
title = 'product details';
productCode='PROD_P001';
productName='AppleMPTT2MacBookPro';
productPrice = 217021;
purchaseDate='1/17/2018';
productTax='0.1';productRating=4.92;
}
App.component.html
<h3>{{title|titlecase}}</h3>
<tablestyle="text-align:left">
<tr>
<th>ProductCode</th>
<td>{{productCode|slice:5:9}}</td>
</tr><tr>
<th>ProductName</th>
<td>{{productName|uppercase}}</td>
</tr><tr>
<th>ProductPrice</th>
<td>{{productPrice|currency:'INR':'symbol':'':'fr'}}</td>
</tr>
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:
PageNo.:
Date:
<tr>
<th>PurchaseDate</th>
<td>{{purchaseDate| date:'fullDate'|lowercase}}</td>
</tr><tr>
<th>ProductTax</th>
<td>{{ productTax|percent:'.2'}}</td>
</tr><tr>
<th>ProductRating</th>
<td>{{productRating|number:'1.3-5'}}</td>
</tr></table>
App.module.ts
import{BrowserModule}from'@angular/platform-browser'; import {
NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { registerLocaleData } from '@angular/common';
importlocaleFrenchfrom'@angular/common/locales/fr';registerLocaleData(localeFrench); @NgModule({
declarations:[AppComponent],
imports: [ BrowserModule],
providers: [],
bootstrap:[AppComponent]})
export class AppModule { }
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 5 8
Expt. No:
PageNo.:
Date:
5c)CourseName: AngularJS
ModuleName:NestedComponents Basics
Aim:LoadCourseslistComponentintherootcomponentwhenauserclicksontheViewcourses
Description:NestedComponentsBasicsinAngularJS
Objective: Learn how to use nested components in AngularJS by loading the
CoursesListComponentinsidethe root component whenauser clicks the"View CoursesList"button.
KeyTopics Covered:
UnderstandingNestedComponents
InAngular, nested components allow breaking alargeUI intosmaller,reusablecomponents. The
root component (usually AppComponent)can load child components dynamically.
CreatingtheCoursesListComponent
Definea componenttodisplayalistofcourses.
UsingPropertyBindingandEventHandling
ImplementabuttonclicktotogglethedisplayofCoursesListComponent.
Program:
courses-list.component.ts
selector:'app-courses-list',
template: `
<h3>AvailableCourses</h3>
<ul>
<li*ngFor="letcourseofcourses">{{course}}</li>
</ul>
`,styleUrls:['./courses-list.component.css']
})
exportclassCoursesListComponent{
courses:string[]=['AngularBasics','ReactFundamentals','Vue.jsIntroduction'];
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:
PageNo.:
Date:
}
app.component.ts
import {Component }from'@angular/core';
@Component({
selector:'app-root',
template:
<button(click)="toggleCoursesList()"> {{ showCourses ? 'Hide Courses List': 'View Courses
List' }} </button>
<app-courses-list*ngIf="showCourses"></app-courses-list>
`,styleUrls:['./app.component.css']
})
export class AppComponent {
showCourses = false;
toggleCoursesList()
{this.showCourses=!this.showCourses;
}
}
app.module.ts
import{ NgModule}from'@angular/core';
import{BrowserModule}from'@angular/platform-browser'; import {
AppComponent } from './app.component';
import {CoursesListComponent }from'./courses-list/courses-list.component'; @NgModule({
declarations: [ AppComponent,CoursesListComponent ],
imports: [BrowserModule],
providers:[],
bootstrap:[AppComponent]
})
exportclassAppModule{}
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:
PageNo.:
Date:
Output:
BeforeClickingtheButton:
[ View Courses List
]AfterClickingtheButton:
[ Hide Courses List ]
Available Courses
- AngularBasics
- ReactFundamentals
- Vue.jsIntroduction
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:6
PageNo:
Date:
Experiment-6
CourseName:AngularJS
ModuleName:PassingdatafromContainerComponenttoChildComponent
Aim: Create an AppComponent that displays a dropdown with a list of courses as values in it. Create
anothercomponentcalledtheCoursesListcomponentandloaditinAppComponentwhichshoulddisplay
thecoursedetails.Whentheuserselectsacoursefromthedropdown,correspondingcoursedetailsshould be
loaded
Description: PassingdatafromaContainerComponenttoaChild ComponentinAngularisacommonuse
casethatinvolvesusing@Input()propertybinding.TheContainerComponentistheparent component,and the
Child Component is the one that receives data from the parent.
Key Concept:@Input()Binding
@Input()isadecoratorthatallows youtopassdatafromaparent(container)componenttoachild
component.
Theparentcomponent bindsthedatatothechildcomponent’s@Input()property, whichallowsthe child
component to receive the data and use it.
StepsforPassingDatafromContainertoChildComponent
1. CreatetheContainerComponent(ParentComponent)
Thecontainercomponent willberesponsibleforholdingthedataandpassingittothechildcomponent.
2. CreatetheChildComponent
Thechildcomponentwilluse@Input()toreceivethedatapassedbytheparent.
Program:
<div>
<h1>WelcometoCourseApp</h1>
<labelfor="courseSelect">SelectaCourse:</label>
<selectid="courseSelect"[(ngModel)]="selectedCourse">
<option*ngFor="letcourseofcourses"[value]="course">History01</option>
<option*ngFor="letcourseofcourses"[value]="course">Science02</option>
<option*ngFor="letcourseofcourses"[value]="course">Maths03</option>
<option*ngFor="letcourseofcourses"[value]="course">Biology04</option>
<option*ngFor="letcourseofcourses"[value]="course">Economics</option>
</select>
<app-courses-list[selectedCourse]="selectedCourse"></app-courses-list>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
</div>
<div*ngIf="selectedCourse">
<h2>CourseDetails</h2>
<table>
<tr>
<th>CourseName</th>
<th>Instructor</th>
<th>StartDate</th>
</tr>
</table>
</div>
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
CourseName:AngularJS
ModuleName:PassingdatafromChildComponenttoContainerComponent
Aim: Create an AppComponent that loads another component called the CoursesList component. Create
anothercomponentcalledCoursesListComponentwhichshoulddisplaythecourseslistinatablealongwith a
register .button in each row. When a user clicks on the register button, it should send that courseName
value back to AppComponent where it should display the registration successful message along with
courseName
Description: Passing data from a Child Component to a Container (Parent) Component in Angular is a
commonrequirement.Thiscanbeachievedbyusing@Output()alongwithEventEmitter.Thebasicideais that the
child component will emit anevent, andtheparent component listens forthatevent to receivethe data.
.KeyConcept:@Output()andEventEmitter
@Output()allowsthechildcomponenttosenddatatotheparentcomponent.
EventEmitterisaclassthathelpscreatecustomeventsinAngular.Thechildcomponentusesitto emit
events, and the parent component listens to them.
StepsforPassingDatafromChildtoParent
1. CreatetheParent(Container) Component
Theparentcomponentwilllistenforthecustomeventemittedbythechildcomponent.
2. CreatetheChildComponent
Thechildcomponentwillemitanevent,sendingdatatotheparentcomponent.
Program:
app.component.html
<div>
<h1>WelcometoCourseRegistrationApp</h1>
<app-courses-list></app-courses-list>
</div>
courses-list.component.html
<table>
<thead>
<tr>
<th>CourseName</th>
<th>Instructor</th>
<th>StartDate</th>
<th>Action</th>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
</tr>
</thead>
<tbody>
<tr*ngFor="letcourseofcourses">
<td>{{course.name}}</td>
<td>{{course.instructor}}</td>
<td>{{course.startDate}}</td>
<td><button(click)="register(course)">Register</button></td>
</tr>
</tbody>
</table>
courses-list.component.ts
import{Component }from'@angular/core';
@Component({
selector:'app-courses-list',
templateUrl: './courses-list.component.html',
styleUrls:['./courses-list.component.css']
})
export classCoursesListComponent {
courses= [
{name:'Math101',instructor:'JohnDoe',startDate:'2023 -09-15'},
{name:'History202',instructor:'JaneSmith',startDate:'2023 -09-20'},
{name:'Science303',instructor:'DavidJohnson',startDate:'2023-09-25'},
];
register(course:any){
alert(`Youhaveregisteredfor${course.name}`);
}
}
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
6c.)CourseName:AngularJS
ModuleName:ShadowDOM
Aim:ApplyShadowDOMandNoneencapsulationmodestocomponents.
Description: The Shadow DOM is a web standard that allows developers to encapsulate a part of a
webpage'sDOM(DocumentObjectModel)andstyleitindependentlyfromtherestofthepage.Itprovides
awaytocreateencapsulatedcomponentswherethecomponent'sinternalDOMandstylesdonotaffectthe
globaldocumentandviceversa.TheShadowDOMispartoftheWebComponentsspecification,whichis
designed to allow reusable, encapsulated components on the web.
Angularprovidesthreeencapsulationmodesforstyleencapsulation:
1. Emulated(default)-AngularemulatestheShadowDOMbyaddingstylesscopedtothecomponent.
2. ShadowDom-UsesthenativeShadowDOMforstylingencapsulation.
3. None-Noencapsulation,meaningthestylesareglobalandaffecttheentiredocument.
Program:
shadow-dom-example.component.ts
import{Component,ViewEncapsulation}from'@angular/core';
@Component({
selector:'app-shadow-dom-example',
templateUrl:'./shadow-domexample.component.html',
styleUrls: ['./shadow-dom-example.component.css'],
encapsulation: ViewEncapsulation.ShadowDom
})exportclassShadowDomExampleComponent{
title='ThiscontentisinsidetheShadowDOM';
}
shadow-dom-example.component.html
<!--src/app/shadow-dom-example/shadow-dom-example.component.html-->
<divclass="shadow-dom-example">
<p>ThiscontentisinsidetheShadowDOM.</p>
</div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
output:
NoneEncapsulation
none-encapsulation-example.component.ts
import{Component,ViewEncapsulation}from'@angular/core';
@Component({
selector:'app-none-encapsulation-example',
templateUrl: './none-encapsulation-example.component.html',
styleUrls: ['./none-encapsulation-example.component.css'],
encapsulation:ViewEncapsulation.None //ApplyNoneencapsulationmode
})
exportclassNoneEncapsulationExampleComponent{
title='ThiscontentisinsidetheNoneEncapsulation';
none-encapsulation-example.component.html
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:6
PageNo:
Date:
<!--src/app/none-encapsulation-example/none-encapsulation-example.component.html-->
<divclass="none-encapsulation-example">
<p>Thiscontentisnotencapsulatedandcanaffectothercomponents.</p>
</div>
Output
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
EXPERIMENT-7
CourseName:Angular JS
ModuleName:TemplateDrivenForms
Aim:Createacourseregistrationformasatemplate-drivenform.
Description:
Template Driven Form in Angular means managing form input and validation primarily through
HTML templates, using Angular directives like ngModel for two-way data binding and ngForm
for form management. This approach is ideal for simpler forms where most of the logic and
validation are handled directly within the template, making it simple to implement and
understand.
Approach:
TocreateaTemplateDrivenForm,weneedtocreateanAngularApplication.
InthenewlycreatedHTMLfile,createaformusinganangulartemplate-drivenapproach.Use
Angular's form directives 'ngModel' to bind form fields.
Addformcontrolssuchas'input'fields.UseValidationsDirectivessuchasrequired,maxlength,
minlength, etc.
Openthetsfileanddefinepropertiesaccordingtoformfields.
Aformwillbesubmittedonlywhenalltherequiredfieldsarefilled.
StepstoCreateTemplate-DrivenForminAngular
Step1:InstallAngularCLI
Ifyouhaven’tinstalledAngularCLIyet,installitusingthefollowingcommand npm
install -g @angular/cli
Step 2:CreateaNew AngularProject
ngnew my-angular-app --no-standalone
cd my-angular-app
Step3:CreateaComponent
nggeneratecomponentuser-form
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
Program:
course-registration-form.component.html
<form#courseRegistrationForm="ngForm"(ngSubmit)="submitForm(courseRegistrationForm)">
<divclass="form-group">
<labelfor="name">FullName:</label>
<inputtype="text"id="name"name="name"ngModelrequired>
</div>
<divclass="form-group">
<labelfor="email">Email:</label>
<inputtype="email"id="email"name="email"ngModelrequiredemail>
</div>
<divclass="form-group">
<labelfor="phone">PhoneNumber:</label>
</div>
<divclass="form-group">
<labelfor="course">SelectaCourse:</label>
<selectid="course"name="course"ngModelrequired>
<optionvalue="">Selectacourse</option>
<optionvalue="course1">Course1</option>
<optionvalue="course2">Course2</option>
<optionvalue="course3">Course3</option>
</select>
</div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
<divclass="form-group">
<labelfor="comments">Comments:</label>
<textareaid="comments"name="comments"ngModel></textarea>
</div
<buttontype="submit"[disabled]="!courseRegistrationForm.valid">Submit</button>
</form>
course-registration-form.component.ts
body{
font-family:Arial,sans-serif;
margin:0;
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
padding:0;
background-color:#f4f4f4;
}
.container{
max-width: 800px;
margin:0 auto;
padding:20px;
background-color:#fff;
box-shadow:02px4pxrgba(0,0,0,0.1);
}
h1{
font-size: 24px;
margin-bottom:20px;
}
app.component.html
<divclass="container">
<h1>{{title}}</h1>
<app-course-registration-form></app-course-registration-form>
</div>app.component.ts
import{Component}from'@angular/core';
@Component({
selector:'my-app',
templateUrl:'./app.component.html',styleUrls:['./app.component.css']
})
exportclassAppComponent{
title='CourseRegistrationApp';
}
app.module.ts
import{NgModule}from'@angular/core';
import{BrowserModule}from'@angular/platform-browser';import{FormsModule} from'@angular/forms';
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
import{AppComponent}from'./app.component';
import{CourseRegistrationFormComponent}from'./course-registration-form/course-registration-
form.component';
@NgModule({ declarations:[
AppComponent,
CourseRegistrationFormComponent
],
imports:[
BrowserModule,FormsModule
],
providers:[],
bootstrap:[AppComponent]
})
exportclassAppModule{}
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
CourseName:Angular JS
Aim:Createanemployeeregistrationformasareactiveform.
Description:
Reactive Forms in Angular allow for managing form inputs and validation through TypeScript logic
instead of relying on HTML templates. This approach provides better control over form state, dynamic
validation, and form grouping, making it ideal for complex applications. Unlike Template-Driven
Forms, Reactive Forms use FormGroup, FormControl, and FormBuilder to define and manage form
structures in the component class.
Approach:
TocreateanEmployeeRegistrationFormusingReactiveForms,wewill:
1. SetupanAngularprojectandconfiguretherequiredmodules.
2. UseFormBuildertocreateandmanageformcontrolsintheTypeScriptfile.
3. BindtheformtotheHTMLtemplateusingthe[formGroup]directive.
4. Handleformsubmissionandvalidationinthecomponentclass.
5. Resettheformuponsuccessfulsubmission.
Stepstoimplement:
Step1:SetUptheAngularProject.
EnsureAngularisinstalledandcreateanewAngularproject(ifnotalreadycreated).
ngnewangular-forms-demo
cd angular-forms-demo
npm install
Step2:ImportRequiredModules.
Modifyapp.module.tstoincludeReactiveFormsModuleforhandlingReactiveForms.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
Step3:CreatetheEmployeeFormUsingFormBuilder.
DefinetheformstructureusingFormGroupandFormBuilderinapp.component.ts.
Step4:BindtheForminHTML
Createtheformlayoutinapp.component.html.UseAngular’s[formGroup]directiveforbindingform controls.
Customizestyles in app.component.css.
Program:
app.component.html:-
<div>
<h2>EmployeeRegistrationForm</h2>
<form[formGroup]="employeeForm"(ngSubmit)="onSubmit()">
<divclass="form-group">
<labelfor="firstName">FirstName:</label>
<inputtype="text"id="firstName"formControlName="firstName"class="formcontrol">
</div>
<divclass="form-group">
<labelfor="lastName">LastName:</label>
<inputtype="text"id="lastName"formControlName="lastName"class="formcontrol">
</div>
<divclass="form-group">
<labelfor="email">Email:</label>
<inputtype="email"id="email"formControlName="email"class="form-control">
</div>
<divclass="form-group">
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
<labelfor="phone">PhoneNumber:</label>
<inputtype="tel"id="phone"formControlName="phone"class="form-control">
</div>
<buttontype="submit"class="btnbtn-primary">Submit</button>
</form>
<divclass="message">
{{formMessage}}
</div>
</div>
app.component.ts:-
import{FormBuilder,FormGroup}from'@angular/forms';
@Component({
selector:'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponentimplementsOnInit{ employeeForm:
FormGroup;
ngOnInit() {
this.employeeForm=this.fb.group({
firstName: [''],
lastName:[''],
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
email:[''],
phone:['']
});
onSubmit(){
if (this.employeeForm.valid) {
console.log(this.employeeForm.value);
this.employeeForm.reset();
}else{
this.formMessage='Fill inalldetailscorrectly.';
app.module.ts:-
import{BrowserModule}from'@angular/platform-browser'; import
@NgModule({
declarations: [
AppComponent
],
imports:[
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
BrowserModule,
ReactiveFormsModule,//Addthisline
],
providers:[],
bootstrap:[AppComponent]
})
exportclassAppModule{}
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
CourseName:Angular JS
ModuleName:CustomValidatorsinReactiveForms
Description:
Custom validators in Angular Reactive Forms allow us to define specific validation rules that are not
available in built-in validators. Unlike default validators such as Validators.required orValidators.email,
a custom validator gives more control over form validation logic.
Approach:
1. SetupanAngularprojectandimportthenecessarymodules.
2. ModifytheEmployeeRegistration FormusingReactiveForms.
3. Createacustomemailvalidatorasaseparatefunction.
4. ApplythevalidatortotheemailfieldinFormGroup.
5. Showvalidationmessagesinthetemplate.
6. Handleformsubmissionandresettheformaftersuccessfulsubmission.
StepstoImplement:
Step1:SetUptheAngularProject
EnsureAngularisinstalledandcreateanewAngularproject(ifnotalreadycreated).
ngnew angular-custom-validator
cd angular-custom-validator
npm install
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:7
PageNo:
Date:
Step2:ImportRequiredModules
Modifyapp.module.tstoincludeReactiveFormsModule.
Step4:BindtheForminHTMLandDisplayErrorMessages
Modifyapp.component.htmltoshowvalidationmessageswhentheemailisincorrect.
Customizestyles in app.component.css.
Program:
app.component.html:-
<div>
<h2>EmployeeRegistrationForm</h2>
<form[formGroup]="employeeForm"(ngSubmit)="onSubmit()">
<divclass="form-group">
<labelfor="firstName">FirstName:</label>
<inputtype="text"id="firstName"formControlName="firstName"class="formcontrol">
</div>
<divclass="form-group">
<labelfor="lastName">LastName:</label>
<inputtype="text"id="lastName"formControlName="lastName"class="formcontrol">
</div>
<divclass="form-group">
<labelfor="email">Email:</label>
<inputtype="email"id="email"formControlName="email"class="form-control">
</div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
<divclass="form-group">
<labelfor="phone">PhoneNumber:</label>
<inputtype="tel"id="phone"formControlName="phone"class="form-control">
</div>
<buttontype="submit"class="btnbtn-primary">Submit</button>
</form>
<divclass="message">
{{formMessage}}
</div>
</div>
app.component.ts:-
import{Component,OnInit}from'@angular/core';
import{FormBuilder,FormGroup,Validators}from'@angular/forms'; @Component({
selector:'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
exportclassAppComponentimplementsOnInit{ employeeForm:
FormGroup;
ngOnInit() {
this.employeeForm=this.fb.group({
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
firstName:['', Validators.required],
lastName:['',Validators.required],
email:['',[Validators.required, Validators.email]],
phone:['',[Validators.required,Validators.pattern(/^\d{10}$/)]]
});
onSubmit(){
if(this.employeeForm.valid){
this.employeeForm.reset();
}else{
this.formMessage='Fill inalldetailscorrectly.';
app.module.ts:-
import{BrowserModule}from'@angular/platform-browser'; import
@NgModule({
declarations: [
AppComponent
],
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:7
PageNo:
Date:
imports: [
BrowserModule,
ReactiveFormsModule,//Addthis line
],
providers:[],
bootstrap:[AppComponent]
})
exportclassAppModule{}
Output:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:8
PageNo:
Date:
Experiment-8
8a)CourseName:AngularJS
ModuleName:CustomValidatorsinTemplateDrivenforms
Aim:Createacustomvalidatorfortheemailfieldinthecourseregistrationform.
Description:
A custom validator is a function that you create to validate form controls based on specific criteria. This
validator is applied to a form control, and it either returns null (indicating the value is valid) or an error
object (indicating the value is invalid). Custom validators can be used for complex validation rules, like
validating an email with a specific domain, ensuring certain patterns, or validating that two form fields
match.
StepstoCreateaCustomValidatorfortheEmailFieldinaCourseRegistration Form
In the context of a course registration form, you may need a custom email validator to ensure that the
email entered bythe user is valid and possiblymeets certain criteria, such as being from aspecific domain
(e.g., only emails from example.com are allowed).
1. CustomValidatorLogic
Thefirststepistodefinethelogicforthevalidator.Forexample,foranemailvalidator,youmightwant to check
the following:
Ensuretheemailhasavalidformat(e.g.,user@domain.com).
Validatethedomainoftheemail(e.g.,onlyallowemailsfromschool.edu).
Thecustomvalidatorwillchecktheemailfieldvalueandreturn:
nulliftheemailisvalid(i.e.,thedomainmatchesyourcriteria).
Anerrorobjectiftheemailisinvalid(e.g.,iftheemaildoesn'tcontaintheexpecteddomain).
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
2 2 A 9 1 A 6 1 7 3
Expt.No:8
PageNo:
Date:
2. ApplytheValidatorintheTemplate
TheemailfieldwillbelinkedtothecustomvalidatorthroughAngular’sngModeldirective,which binds
the field to the form control.
Ifthevalidationfails,Angularwillsetanerrormessageordisplayavalidationmessage,whichcan be used
in the HTML template to alert the user that the entered email is invalid.
Program:
//app.component.html
<form[formGroup]="registrationForm">
<!--Otherformfields-->
<divclass="form-group">
<labelfor="email">Email:</label>
<!--Displayamessagewhenemailisvalid-->
<div*ngIf="submitted&®istrationForm.get('email').valid"class="text-success">Correct
</div>
<!--Displayanerrormessagewhenemailisinvalid -->
<div*ngIf="submitted&®istrationForm.get('email').hasError('invalidEmail')"class
="text-danger">
Invalidemailformat.
</div>
</div>
<!--Submitbutton-->
<button(click)="onSubmit()">Submit</button>
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
</form>
//app.component.ts:
import{Component}from'@angular/core';
import{emailValidator}from'./app.module';//Importthecustomvalidator
@Component({
selector:'my-app',
templateUrl:'./app.component.html',styleUrls:['./app.component.css'],
})
});
onSubmit(){
this.submitted=true;//Settheflagtotrueonsubmit if
(this.registrationForm.valid) {
console.log('Formsubmittedsuccessfully');
//app.module.ts:
import{NgModule}from'@angular/core';
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:8
PageNo:
Date:
import{BrowserModule } from'@angular/platform-browser'; import
import{ReactiveFormsModule}from'@angular/forms';
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
})
exportclassAppModule{}
exportfunctionemailValidator(control:any){
constemailPattern= /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;if(control.value&&
!emailPattern.test(control.value)){
returnnull;
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
8b)CourseName:AngularJS
ModuleName:ServicesBasics
Aim:CreateaBookComponentwhichfetchesbookdetailslikeid,nameanddisplaysthemonthepage in a list
format. Store the book details in an array and fetch the data using a custom service.
Description: In Angular, services are used to provide functionality that can be shared across
components. Theyallow you to encapsulate business logic, data management, and utility functions, which
helps in keeping the components clean andfocused on their primary role. Services are often used tohandle
HTTP requests, state management, and data fetching, among other tasks.
In this exercise, we'll create a Book Component that fetches and displays book details like id and name
using a custom service. The data will be stored in an array, and the component will interact with this
service to retrieve and display the book details.
1) CreatetheService:
2) InjecttheServiceintotheComponent:
3) BindDatatotheTemplate:
4) DisplayDatatotheUser:
Program:
//app.component.html:
<!--app.component.html -->
<div>
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
<h1>Welcometomy-app</h1>
<app-book-list></app-book-list>
</div>
//app.component.ts:
import {Component,VERSION}from'@angular/core';
@Component({
selector:'my-app',
templateUrl:'./app.component.html', styleUrls:['./app.component.css']
})
name='Angular'+VERSION.full;
//app.module.ts:
import{NgModule}from'@angular/core';
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent,BookListComponent
],
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
bootstrap:[AppComponent]
})
exportclassAppModule{}
book-list.component.html:-
<!--book-list.component.html-->
<div>
<h2>BookList</h2>
<ul>
<li*ngFor="letbookofbooks">
{{book.name}}
</li>
</ul>
</div>
//book-list.component.ts
import{Component,OnInit}from'@angular/core';import{BookService}from'./book.service';
@Component({
selector:'app-book-list',
templateUrl:'./book-list.component.html',styleUrls:['./book-list.component.css'],
})
exportclassBookListComponentimplementsOnInit{books:{id:number;name:string}[]=[];
ngOnInit():void{
this.bookService.getBooks().subscribe((books)=>{this.books =books;
});
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:8
PageNo:
Date:
}
// book.service.ts
import{Injectable}from'@angular/core';import{Observable,of}from'rxjs';
})
exportclassBookService{
privatebooks:{id:number;name:string}[]=[
{id:1,name:'Book1'},
{id:2,name:'Book2'},
{id:3,name:'Book3'},
];
getBooks():Observable<{id:number;name:string}[]>{returnof(this.books);
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
8c)CourseName:AngularJS
ModuleName:RxJSObservables
Aim:CreateanduseanObservableinAngular.
Description: In Angular, RxJS Observables are used for handling asynchronous data streams, events,
and responses. The Observable pattern allows you to manage data that is produced over time, such as
HTTP requests, user input events, or any other kind of data that can change asynchronously.
Observablesallowcomponentsandservicestosubscribetoandreceivedatawhenit'sready.Theycan
handlemultiple events, emit values, and evensupport advancedoperators like map, filter, and merge.
Step-by-StepProcess:
1. ObservableCreation:
o AnObservableiscreatedusingeitheranObservableconstructororhelpermethodslike of(),
from(), or interval().
o YouwouldtypicallycreateanObservableinaservicewheredataneedstobefetchedor
processed asynchronously.
2. Subscription:
o OncetheObservableiscreated, componentsorservicescansubscribetotheObservable. This
is how they "listen" to the emitted values over time.
o WhentheObservableemitsavalue(orcompletes),thesubscriptionwillreacttoit
accordingly.
3. Unsubscription:
o Unsubscribing is important to avoid memory leaks, especially when the component is
destroyedornolongerneedsthedata.AngularprovidesangOnDestroy()lifecyclehookfor
cleaning up subscriptions.
4. RxJSOperators:
o YoucanusearangeofRxJSoperators(likemap(),filter(),merge())tomanipulatedata
emitted by an Observable before the subscription.
Program:
//appmodule.ts
import{NgModule}from
'@angular/core';
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
import{BrowserModule}from
'@angular/platform-browser';
import{AppComponent}from
'./app.component';
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
bootstrap:[AppComponent]
})
exportclassAppModule{}
//appcomponent.ts
import{Component,OnInit}
from '@angular/core';
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
import{DataService}from
'./data.service';
@Component({
selector:'my-app',
templateUrl:
'./app.component.html',
styleUrls:['./app.component.css'],
})
exportclassAppComponent
implements OnInit {
data:string;
constructor(privatedataService:
DataService) {}
ngOnInit():void{
this.dataService.getData().subscrib
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
e((result) => {
this.data=result;
});
//appcomponent.html
<div>
<h1>Welcometo my-app</h1>
<p>DatafromObservable:</p>
<p>{{data}}</p>
</div>
//dataservice.ts
import{Injectable}from
'@angular/core';
import{Observable,of}from
'rxjs';
@Injectable({
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:8
PageNo:
Date:
providedIn:'root',
})
getData():Observable<string>{
constdata='Thisissomedata
from an observable!';
returnof(data);
Output:
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:9
PageNo.:
Date:
Experiment-9
9.aCourseName:AngularJS
ModuleName:ServerCommunicationusingHttpClient
Aim:CreateanapplicationforServerCommunicationusingHttpClient.
Description:
1. OverviewofHttpClientinAngularJS
HttpClient isa service inAngular that allows you to interact with backend servers via HTTP
protocols (GET, POST, PUT, DELETE, etc.).
Itisusedtofetchdatafrom orsenddatatoaserverinyourAngularapplication.
2. KeyConcepts
HttpClientModule:AmoduleyouimportinyourAngularapplication touse theHttpClientservice.
Observable: HttpClient methods return Observables, which allow asynchronous operations. You
subscribe to these Observables to handle the data when it's received.
HttpMethods:
GET:Fetchdatafromtheserver.
POST: Send data to the server.
PUT: Update existingdata onthe server.
DELETE:Removedatafromtheserver.
3. StepsInvolved
ImportHttpClientModule:
InjectHttpClientService:
The HttpClient service is injected into the component or service where you want to make HTTP
requests.
MakingHTTPRequests:
UseHttpClientmethodslike.get(),.post(),.put(),.delete()tointeractwiththebackendserver.
The data returned fromthese methods is handled via Observables, so you subscribe to the
Observable to retrieve and process the data.
Error Handling:It’s important to handle errors when making HTTP requests. Angular provides
operators like catchError to manage errors effectively.
Binding Data to the UI:After successfully fetching or sending data, you can bind the response to
the component's view in Angular using data binding.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:9
PageNo.:
Date:
Updating Data: Sending modified data to the server to update records (e.g., editing user profiles).
Error Handling: Displaying appropriate error messages when a request fails.
ObservablesandSubscription
ObservablesareacorepartofRxJSinAngular.
YousubscribetotheseObservablestohandlesuccessorerroreventswhenarequestcompletes.
Program:
Step1:CreateaService Name:data
Step2:ImplementtheService
Data.service.ts
import{Injectable}from'@angular/core';
import { HttpClient }from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn:'root'
})
exportclassDataService{
private apiUrl = 'https://jsonplaceholder.typicode.com'; // Replace with your server URL
constructor(private http: HttpClient) { }
getData():Observable<any>{
returnthis.http.get(`${this.apiUrl}/posts/1`);//ReplacewithyourAPIendpoint
}
}
Step4:CreateaComponent
Name:data-display
data-display.component.ts
import {Component, OnInit }from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector:'app-data-display',
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:9
PageNo.:
Date:
templateUrl:'./data-display.component.html',
styleUrls: ['./data-display.component.css']
})
export class DataDisplayComponent implements OnInit {
data: any;
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.getData().subscribe(response => {
this.data=response;
});
}
}
Step5:CreateaComponentTemplate
data-display.component.html
<div*ngIf="data">
<h2>DatafromtheServer:</h2>
<pre>{{data|json}}</pre>
</div>
app.component.html:
<app-data-display></app-data-display>
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http'; // Import HttpClientModule
import { AppComponent } from './app.component';
import { DataDisplayComponent } from './data-display/data-display.component';
import { DataService } from './data.service';
@NgModule({
declarations: [
AppComponent,
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt. No:9
PageNo.:
Date:
DataDisplayComponent
],
imports: [
BrowserModule,
HttpClientModule,//AddHttpClientModuletotheimportsarray
],
providers: [DataService],
bootstrap:[AppComponent]
})
exportclassAppModule{}
Output:
The data received fromthe server inJSON format. It includesthe following fields:
userId : The ID of the user.
Id : The ID of the data entry.
Title:Thetitleofthedataentry.
Body:Thebodyorcontentofthedataentry.
This is a typical response from a JSON API, and your Angular application has successfully
fetched and displayed this data from the server. You can now use this data as needed within
your application.
9b.CourseName: AngularJS
ModuleName:CommunicatingwithdifferentbackendservicesusingAngularHttpClient
Aim:Create a custom service called ProductService in which Http class is used to fetch data
stored in the JSON files.
Description:
IntroductiontoAngularHttpClient
UnderstandingBackendServices
TypesofBackendServicesinAngular
CommunicatingwithRESTAPIsUsingHttpClient
1. GET(RetrieveData)
Purpose:FetchdatafromtheserveroraremoteAPI.
TypicalUse Case: Retrieving a list of items (like users, products, or posts)or a specific
resource by ID.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:9
PageNo.:
Date:
HttpClientmethod:get()
2. POST(SendData)
Purpose:Senddatatotheservertocreate anewresource.
TypicalUseCase:Submittingformdatatocreateanewuseroritemin adatabase.
HttpClientmethod:post()
3. PUT(UpdateData)
Purpose:Updateanexistingresourceontheserver.
TypicalUseCase:Editinganexistinguserprofileormodifyinganitem.
HttpClientmethod:put()
4. DELETE(RemoveData)
Purpose:Removearesourcefromtheserver.
TypicalUseCase:Deletingauseroranitemfromthedatabase.
HttpClientmethod:delete()
Program:
Product-list.component.ts:
import {Component, OnInit }from '@angular/core';
import { ProductService } from './product.service';
@Component({
selector:'app-product-list',
templateUrl:'./product-list.component.html',
styleUrls: ['./product-list.component.css']
})
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:9
PageNo.:
Date:
export class ProductListComponent implements OnInit {
products: any[] = [];
constructor(private productService: ProductService) { }
ngOnInit() {
this.productService.getProducts().subscribe((data) => {
this.products=data;
});
}
}
Product.service.ts:
import{Injectable}from'@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn:'root'
})
exportclassProductService{
privateproductsUrl='assets/products.json';
constructor(private http: HttpClient) { }
getProducts(): Observable<any[]> {
returnthis.http.get<any[]>(this.productsUrl);
}
}
App.component.html:
<div*ngIf="products.length>0;elsenoProducts">
<h2>Products</h2>
<ul>
<li*ngFor="letproductofproducts">
<h3>{{product.name}}</h3>
<p>Price:{{product.price}}</p>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:9
PageNo.:
Date:
<p>Description:{{product.description}}</p>
</li>
</ul>
</div>
<ng-template#noProducts>
<p>Noproductsavailable</p>
</ng-template>
App.component.ts:
import{ Component,OnInit}from'@angular/core';
import { ProductService } from './product-list/product.service';
@Component({
selector: 'my-app',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
products: any[] = [];
constructor(private productService: ProductService) { }
ngOnInit() {
this.productService.getProducts().subscribe((data) => {
this.products=data;
});
}
}
App.module.ts:
import{NgModule}from'@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt. No:9
PageNo.:
Date:
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers:[],
bootstrap:[AppComponent]
})
exportclassAppModule{}
Output:
Products
Product1
Price:100
Description:DescriptionofProduct1
Product2
Price:150
Description:DescriptionofProduct2
Product3
Price:200
Description:DescriptionofProduct3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
Experiment-10
CourseName:AngularJS
ModuleName:RoutingBasics,RouterLinks
Aim:Createmultiplecomponentsandaddroutingtoprovidenavigationbetweenthem.
Description:
Objective:Theobjective ofthis experiment is toimplement routing in anAngular application. You
will create multiple components and set up navigation between them using Angular’s Router and
Router Links.
Requirements:
Node.jsinstalled.
AngularCLIinstalled.
BasicunderstandingofAngularframeworkandcomponents.
Program:
app-routing.module.ts:
import{NgModule}from'@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{path:'home',component:HomeComponent},
{path:'about',component:AboutComponent},
@NgModule({
imports:[RouterModule.forRoot(routes)],exports:[RouterModule]
})
exportclassAppRoutingModule{}
app.component.html:
<nav>
<arouterLink="/home">Home</a>
<arouterLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
app.component.ts:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
templateUrl:'./app.component.html',styleUrls:['./app.component.css']
})
exportclassAppComponent{
}
app.module.ts:
import{NgModule}from'@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations:[AppComponent],
imports:[BrowserModule,AppRoutingModule,RouterModule],//AddRouterModulehere bootstrap:
[AppComponent]
})
exportclassAppModule{}
about.component.html:
<p>
mst</p>home.component.html:
<p>Meanstacktechnologies</p>
Output:
HomeAbout
Mst
HomeAbout
Meanstacktechnologies
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
CourseName:AngularJS
ModuleName:RouteGuards
Aim: Considering the same example used for routing, add route guard to BooksComponent.
Onlyafterloggingin,theusershouldbeabletoaccessBooksComponent.Iftheusertriestogivethe URL of
Bookscomponent in another tab or window, or if the user tries
Description:ThegoalofthisexperimentistoimplementRouteGuardsinAngular.Specifically, we want to
secure the BooksComponent such that only authenticated users can access it. If an
unauthenticatedusertriestoaccesstheBooksComponentthroughdirectURLnavigation,they will be
redirected to the login page.
Stepsfor implementation:
1. Createa NewAngularApplication:
Youcanstart bycreating a newAngular application and navigatingto its folder: ng
new angular-routing-guard
cdangular-routing-guard
2. GenerateComponents:
Generate components for Home, About, Contact, Books, and Login.
ng generate component home
ng generate component about
nggeneratecomponentcontact
ng generate component books
ng generate component login
3. GenerateAuthServiceandAuthGuard:
Generate a service for handling authenticationand a route guardto protect the BooksComponent.
ng generate service auth
ng generateguard auth
Program:
auth.service.ts(AuthenticationService)
import{Injectable}from'@angular/core';
@Injectable({
providedIn:'root'
})
exportclassAuthService{ private
loggedIn = false;
login() {
this.loggedIn=true;
}
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
logout() {
this.loggedIn=false;
}
isLoggedIn()
{returnthis.loggedIn
;
}
}
auth.guard.ts(RouteGuard)
//auth.guard.ts
import{Injectable}from'@angular/core';
@Injectable({
providedIn:'root'
})
export classAuthGuardimplementsCanActivate{
constructor(privateauthService:AuthService,private router:Router){}
canActivate():boolean{
if(this.authService.isLoggedIn()){
returntrue;//AllowaccesstotheBooksComponent
}else{
app-routing.module.ts(RoutingConfiguration):
//app-routing.module.ts
import{NgModule}from'@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {HomeComponent }from'./home/home.component';
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
import { AboutComponent } from './about/about.component';
import { ContactComponent}from'./contact/contact.component';
import { BooksComponent } from './books/books.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
constroutes:Routes=[
{path:'',component:HomeComponent},
{path:'about',component:AboutComponent},
{path:'contact',component:ContactComponent},
{path:'books',component:BooksComponent,canActivate:[AuthGuard]},//ApplyAuthGuard
{path:'login',component:LoginComponent},
];
@NgModule({
imports:[RouterModule.forRoot(routes)],
exports: [RouterModule]
})
exportclassAppRoutingModule{}
login.component.ts:
//login.component.ts
import {Component }from '@angular/core';
import {AuthService }from'../auth.service'; import
{ Router } from '@angular/router';
@Component({
selector:'app-login',
template: `
<h2>Login</h2>
<button(click)="login()">Login</button>
})
exportclassLoginComponent{
constructor(privateauthService:AuthService,privaterouter:Router){}
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
login() {
this.authService.login();
this.router.navigate(['/books']);//Redirecttobookspageafterlogin
}
}
books.component.ts(BooksComponent):
//books.component.ts
import {Component }from '@angular/core';
@Component({
selector:'app-books',
template: `
<h1>BooksList</h1>
<p>ThisistheBooksComponent,visibleonlyafterlogin.</p>
})
exportclassBooksComponent{}
app.component.html:
<!--app.component.html-->
<nav>
<ul>
<li><arouterLink="/">Home</a></li>
<li><arouterLink="/about">About</a></li>
<li><arouterLink="/contact">Contact</a></li>
<li><arouterLink="/books">Books</a></li>
<li><arouterLink="/login">Login</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
app.component.ts:
//app.component.ts
import{Component}from'@angular/core';
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title='angular-routing-guard';
}
Output:
RuntheApplication
Now,runtheAngularapplication: ng
serve
Navigatetohttp://localhost:4200/.
HomePage:
<h1>WelcometotheHomePage</h1>
NavigationBar:
Home
About
Contact
Books
Login
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
Course Name:AngularJS
ModuleName:AsynchronousRouting
Aim: Apply lazy loading to BookComponent. If lazy loading is not added to the demo, it has
loaded in 1.14 s.Observe the load time at the bottom of the browser console. Press F12 in the
browser and click the Network tab and check the Load time.
Description:
Objective:The goal is to implement lazy loading in Angular for the BooksComponent and
observe the difference in load time in the browser's Network tab.
WhatisLazyLoading?
Lazy loading is a design pattern in Angular that allows modules to be loaded only when needed,
rather than when the application is initialized. This can drastically reduce the initial loading time
and improve performance, especially in large applications.
InAngular, lazyloading can be configured for specific feature modules, whichare onlyloaded when
the user navigates to their associated route.
Program:
CreateaNewAngularApplication:
ngnewangular-lazy-loading cd
angular-lazy-loading
2. GenerateComponents
ng generate component home
ng generate component about
nggeneratecomponentcontact
ng generate component books
ng generate component login
3. GenerateBooksModuleforLazyLoading:
nggeneratemodulebooks--routebooks--moduleapp.module
4. Modifyapp-routing.module.tsforLazyLoading
//app-routing.module.ts
import{ NgModule}from'@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import{AboutComponent}from'./about/about.component';
import { ContactComponent } from './contact/contact.component';
import { LoginComponent } from './login/login.component';
constroutes:Routes=[
{path:'',component:HomeComponent},
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
{path:'about',component:AboutComponent},
{path:'contact',component:ContactComponent},
{path:'login',component:LoginComponent},
{path:'books',loadChildren:()=>import('./books/books.module').then(m=>m.BooksModule)}
];
@NgModule({
imports:[RouterModule.forRoot(routes)],
exports: [RouterModule]
})
exportclassAppRoutingModule{}
5. Modifybooks-routing.module.ts:
//books-routing.module.ts
import{NgModule}from'@angular/core';
import{RouterModule,Routes}from'@angular/router';
constroutes: Routes= [
{path:'',component:BooksComponent}
];
@NgModule({
imports:[RouterModule.forChild(routes)],
exports:[RouterModule]
})
exportclassBooksRoutingModule{}
6. Modifybooks.module.tstoDeclareandImportRouting:
//books.module.ts
import { NgModule}from'@angular/core';
import { CommonModule}from'@angular/common';
import { BooksComponent}from'./books.component';
import { BooksRoutingModule}from'./books-routing.module';
@NgModule({
declarations:[BooksComponent],
imports: [
CommonModule,
BooksRoutingModule
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
]
})
exportclassBooksModule{}
7. Modifyapp.component.htmltoIncludeNavigationLinks
<!--app.component.html-->
<nav>
<ul>
<li><arouterLink="/">Home</a></li>
<li><arouterLink="/about">About</a></li>
<li><arouterLink="/contact">Contact</a></li>
<li><arouterLink="/books">Books</a></li>
<li><arouterLink="/login">Login</a></li>
</ul></nav>
<router-outlet></router-outlet>
8. Implementbooks.component.ts:
import{Component}from'@angular/core';
@Component({
selector:'app-books',
template: `
<h1>Books List</h1>
<p>ThisistheBooksComponent,visibleonlyafterlazy loading.</p>
})
exportclassBooksComponent{}
9. Implementhome.component.tsandOtherComponents:
//home.component.ts
@Component({
selector:'app-home',
template: `
<h1>WelcometoHomePage</h1>
<p>Thisisthe homepage oftheapp.</p>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
})
exportclassHomeComponent{}
typescript
Copy
//about.component.ts
import { Component } from'@angular/core';
@Component({
selector:'app-about',
template: `
<h1>AboutUs</h1>
<p>ThisistheAboutpage.</p>
`})
exportclassAboutComponent{}
//contact.component.ts
import { Component } from'@angular/core';
@Component({
selector:'app-contact',
template: `
<h1>ContactUs</h1>
<p>This istheContactpage.</p>
})
exportclassContactComponent{}
//login.component.ts
import { Component } from'@angular/core';
@Component({
selector:'app-login',
template: `
<h1>Login</h1>
<button(click)="login()">Login</button>
`
})
exportclassLoginComponent{
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
login(){
alert("Loggedinsuccessfully!");
}
Output:
RuntheApplication:ngserve
1. OpentheBrowserConsoleandNetworkTab:
Open your browser and go to http://localhost:4200/. Press F12to openthe developer tools
and navigate to the Network tab.
2. ObserveLoadTimeWithoutLazyLoading:
o Iflazyloading isn't enabled, you willseearequest to load the BooksComponent as
soon as the app is initialized.
o TheBooksComponent will load aspart ofthe initialapplication bundle, and you
should observe the load time of the BooksComponent in the network tab.
3. ObserveLoadTimeWithLazyLoading:
o WhenyouclickontheBookslinkforthefirsttime,Angularwillloadthe
BooksModulelazily.
o In the Network tab, you'll see a request forthe BooksModule JavaScript file, which
will be loaded only when the user navigates to /books.
o Thislazyloadingwillimprovetheinitialloadingtimeoftheappasthe
BooksComponentisloadedonlywhenneeded.
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
10.d)CourseName:AngularJS
Aim:ImplementChildRoutestoasubmodule.
1. Angular:
InAngular, child routes are defined inside the RouterModule fora feature module. Thisallows you
to group routes and create nested views. Here's a step-by-step guide:
Step1:CreatetheFeatureModule
First,createthesubmodule(featuremodule)thatwillhavechildroutes.
nggeneratemodulefeature
Step2:DefineChildRoutes
In the feature-routing.module.ts, you can define child routes using the children propertyof the
route object.
feature-routing.module.ts:
import{NgModule}from'@angular/core';
import{RouterModule,Routes}from'@angular/router';
import{FeatureComponent}from'./feature.component';//Parentcomponent
import{SubFeatureComponent}from'./sub-feature/sub-feature.component';//Childcomponent1
constroutes:Routes=[{ path:
'',
component:FeatureComponent,//ParentComponent
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
children:[{
path:'sub-feature',
component:SubFeatureComponent//Childroute1},
{path:'another-sub-feature',
component:AnotherSubFeatureComponent//Childroute2
}]
}];
@NgModule({
imports:[RouterModule.forChild(routes)],
exports: [RouterModule]
})
exportclassFeatureRoutingModule{}
Step3:ConfiguretheParentandChildComponents
In the parent component (feature.component.ts), you need to defineanoutlet where the child routes
will be displayed.
feature.component.html:
<h2>FeatureModule</h2>
<nav><ul>
<li><arouterLink="sub-feature">SubFeature</a></li>
<li><arouterLink="another-sub-feature">AnotherSubFeature</a></li>
</ul></nav>
<router-outlet></router-outlet><!--Herethechildcomponentswillbedisplayed-->
feature.module.ts:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
import{NgModule}from'@angular/core';
import {FeatureComponent}from'./feature.component';
@NgModule({
declarations:[FeatureComponent],
imports:[CommonModule,FeatureRoutingModule]
})
exportclassFeatureModule{}
Step5:AddtheFeatureModuletotheAppModule
Don't forget to include the FeatureModulein your main application module (app.module.ts):
@NgModule({
declarations:[AppComponent],
imports:[BrowserModule,FeatureModule],
bootstrap: [AppComponent]
})
exportclassAppModule{}
FinalDirectoryStructure:
src/
app/
feature/
feature.module.ts
feature.component.ts
feature.component.html
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
feature-routing.module.ts
sub-feature/
sub-feature.component.ts
another-sub-feature/
another-sub-feature.component.ts
2. React:
In React, you can implement child routes using a routing librarylike react-router-dom. Here's how
you can set up child routes:
Step1:Installreact-router-dom
install react-router-dom
Step2:Create Submodule(FeatureComponent)
Let'ssayyouhaveaFeaturecomponentthatwillhavechildroutes.
//Feature.js
importReactfrom'react';
return(
<div>
<h2>FeatureModule</h2>
<nav><ul>
<li><Linkto="sub-feature">SubFeature</Link></li>
<li><Linkto="another-sub-feature">AnotherSubFeature</Link></li>
</ul></nav>
<Outlet/>{/* Thisiswherechildrouteswillrender*/}
</div>
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
);
};
exportdefaultFeature;
Step3:DefineChildComponents
DefinechildcomponentsthatwillberenderedinsidetheFeaturecomponent.
//SubFeature.js
constSubFeature=()=>{
return<div><h3>SubFeatureComponent</h3></div>;
};
exportdefaultSubFeature;
// AnotherSubFeature.js
importReactfrom'react';
constAnotherSubFeature=()=>{
return<div><h3>AnotherSubFeatureComponent</h3></div>;
};
exportdefaultAnotherSubFeature;
Step4:SetUpRoutesintheRouter
Setuptheroutes anddefinetheparentandchildroutesusingtheRoutecomponent.
//App.js
importReactfrom'react';
importSubFeaturefrom'./SubFeature';
importAnotherSubFeaturefrom'./AnotherSubFeature';
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.No:10
PageNo.:
Date:
functionApp(){
return (
<Router>
<Routes>
<Routepath="/"element={<h1>HomePage</h1>}/>
<Routepath="feature"element={<Feature/>}>
<Routepath="sub-feature"element={<SubFeature/>}/>
<Routepath="another-sub-feature"element={<AnotherSubFeature/>}/>
</Route>
</Routes>
</Router>
);
exportdefaultApp;
FinalDirectoryStructureinReact:\
src/
App.js
Feature.js
SubFeature.js
AnotherSubFeature.js
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.no:11
Page No:
Date:
Experiment-11
Aim:InstallingMongoDBonLocalComputer
Description:o install MongoDB on your localcomputer, follow these steps based on your operating
system:
1. DownloadMongoDB:
o Go to the official MongoDB website:
https://www.mongodb.com/try/download/community
o SelectWindows asyouroperatingsystem.
o ChoosetheversionyouwantandclickontheDownloadbutton.
2. InstallMongoDB:
o Openthedownloaded.msifiletostarttheinstallationprocess.
o Followtheinstallationsteps,making suretoselectCompletesetup.
o During installation, ensure you checkthe box to install MongoDBasa Service and
choose to run MongoDB as a Network Service User.
o It’s a good idea to also select theoptionto Install MongoDB Compass (the GUI for
MongoDB) during the installation process.
3. SetUptheEnvironmentVariables:
o Afterinstallation, you need to addMongoDB’s bin directoryto your system’s
PATH environment variable.
o ThedefaultpathforMongoDBisC:\Program
Files\MongoDB\Server\<version>\bin.
o ToaddittothePATH:
Open Control Panel > System> Advanced System Settings > Environment
Variables.
Under System Variables,findthePathvariableandclickEdit.
AddthepathC:\ProgramFiles\MongoDB\Server\<version>\bintothelist.
4. CreatetheDataDirectory:
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.no:11
Page No:
Date:
o MongoDBneeds a data directoryto store its files. Bydefault, MongoDB looks for
data in C:\data\db.
o Tocreatethedirectory,openCommandPromptandrun:
mkdirC:\data\db
5. StartMongoDB:
o Open Command Prompt asAdministratorand runthe followingcommand to start
MongoDB:
mongod
o ThisshouldstarttheMongoDBserver.You’llseelogsshowingit’srunning.
6. ConnecttoMongoDB:
o OpenanotherCommandPromptwindowandrun:
mongo
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.no:11
Page No:
Date:
Aim: Write MongoDB queries to performCRUD operations ondocument using insert(), find(),
update(), remove().
Description: Here are MongoDB queries demonstrating CRUD (Create, Read, Update, Delete)
operations on a document in a collection using insert(), find(), update(), and remove():
1. Create(InsertaDocument)
Example:
//Insertasingledocument
db.users.insert({
name:"JohnDoe",
age: 29,
email:"johndoe@example.com",
isActive: true
});
//Toinsertmultipledocuments,use insertMany():
db.users.insertMany([
{name:"AliceSmith",age:25,email:"alice@example.com",isActive:true},
{name:"BobJohnson",age:34,email:"bob@example.com",isActive:false}
]);
2. Read(FindDocuments)
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.no:11
Page No:
Date:
Example:
//Findalldocumentsintheuserscollection:
db.users.find();
//Finddocumentswithaspecificcondition:
db.users.findOne({name:"JohnDoe"});//Findauserwithname"JohnDoe"
3. Update(UpdateDocuments)
To update documents, you canuse the update() method (or updateOne(), updateMany() in newer
versions). MongoDB also provides the findAndModify() method, but it's more common to use
updateOne() or updateMany() for updating documents.
Example:
//Update asingledocument:
db.users.update(
{name:"JohnDoe"}, // Conditiontomatchthedocument
{$set:{age:30}} //Fieldstoupdate
);
//Updatemultipledocuments:
db.users.updateMany(
{ isActive:false}, //Conditiontomatchthedocuments
{$set:{isActive:true}}//Fieldstoupdate
);
db.users.updateOne(
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
Expt.no:11
Page No:
Date:
{name:"AliceSmith"},
{$inc:{age:1}}
);
4. Delete(RemoveDocuments)
To removedocuments,use theremove()method(ordeleteOne(),deleteMany()innewerversions).
Example:
db.users.remove({isActive: false});
//Deletealldocuments inacollection:
db.users.remove({});
ADITYAENGINEERINGCOLLEGE,SURAMPALEM 2 2 A 9 1 A 6 1 7 3
=
Expt.No:12
PageNo.:
Date:
Experiment-12
CourseName:MongoDBEssentials-ACompleteMongoDBGuide
ModuleName:CreateandDeleteDatabasesandCollections
AIM:WriteMongoDBqueries toCreateanddropdatabasesandcollections.
Description:
CreatingaDatabase:
MongoDB does not require explicit commands to create a database. A database is created
automaticallywhen a collection is first createdor when a document is inserted into a collection. If
you connect to a non-existent database and begin working with it, MongoDB will create that
database for you.
The database willonlybe created ondisk once it contains data, i.e., once you insert a document into
a collection.
DeletingaDatabase:
MongoDB allows you to delete an entire database using a command. Deleting a database removes
all collections and documents within it, and the action is irreversible.
MongoDBprovidesthedropDatabase()methodforthispurpose.
CreatingaCollection:
Acollection in MongoDB is a group ofdocuments. Similar to a database, MongoDB will create a
collection automatically when you insert the first document. However, you can also create a
collection explicitly using the createCollection() method.
Collections do not have a fixed schema, which means documents within a collection can have
different fields.
DeletingaCollection:
MongoDB allows you to delete a collection withthe drop() method. Once a collection is deleted,
all its documents and indexes are removed permanently.
KeyOperations:
CreateaDatabase:
When you connect to MongoDB and switch to a database that does not exist, MongoDB will
automatically createit for you.You can confirm this by checking the list of databases.
DeleteaDatabase:
If you want to delete a database, you canuse the dropDatabase() command. It deletes theentire
database, including all its collections and documents.
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:12
PageNo.:
Date:
CreateaCollection:
You can createa collection explicitlyusing the createCollection() method or it will be created
automatically when a document is added to a non-existent collection.
DeleteaCollection:
Deleting a collection removes it fromthe database along with all its documents. This operation is
irreversible, and MongoDB provides the drop() command to perform this.
CourseName:MongoDBEssentials-ACompleteMongoDBGuide
ModuleName:IntroductiontoMongoDBQueries
Aim: Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(),
aggregate().
Description:
find():
The find() method is the most commonly used query method in MongoDB. It is used to
retrieve documents froma collection. You canspecifyconditions to filter the results, and it
returns a cursor that can be used to iterate over the result set.
Basic Query: You canuse find() to get alldocuments or filter results byspecifyingquery
criteria.
//Findall documentsinacollection
db.collectionName.find()
//Finddocumentswithaspecificfieldvalue
db.collectionName.find({field:value})
// Find documents with a field value matching a range
db.collectionName.find({ age: {$gt: 25, $lt:40 }})
limit():
The limit() method is used to restrict the number ofdocuments returned in a query. This is
useful when you want to retrieve a subset of records rather than the entire dataset,
especially when working with large collections.
Usage: It’s often used in combination with find() to limit the number ofdocuments
returned.
//Limitthenumberofdocumentsreturned
db.collectionName.find().limit(10)
sort():
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM
Expt.No:12
PageNo.:
Date:
The sort() method allows you to sort the results of a queryinascending or descending order
based on one or more fields.
Usage: Sorting can be applied to the results fromfind(), allowing you to displaydata ina
specific order (e.g., by date, price, name).
//Sortdocumentsinascendingorderbyafield
db.collectionName.find().sort({field:1})
//Sortdocumentsin descendingorderbyafield
db.collectionName.find().sort({ field: -1 })
createIndex():
The createIndex() method is used to create indexes on collections to improve query
performance. Indexes are particularlyuseful when you frequentlyquerycertain fields, as they
allow MongoDB to find records faster.
Usage:You can create asingle field index or a compound index, which involves indexing
multiple fields together to optimize queries.
//Createanascendingindexonafield
db.collectionName.createIndex({field:1})
//Createadescendingindexonafield
db.collectionName.createIndex({ field: -1 })
aggregate():
The aggregate() method allows you to performadvanced data processing on the data ina
collection. It allows you to perform operations such as filtering, grouping, sorting, and
reshaping data.
Usage:Aggregation is commonlyused when you need to performoperations like calculating
sums, averages, or grouping data into specific categories.
//Exampleaggregationpipeline:calculateaverageagebygender
db.collectionName.aggregate([{$group:{_id:"$gender",avgAge:{$avg:"$age"}}}
2 2 A 9 1 A 6 1 7 3
ADITYAENGINEERINGCOLLEGE,SURAMPALEM