mst-2 Record4docx
mst-2 Record4docx
LAB MANUAL
CERTIFICATE
Certified that this is a bonafide record of practical work carried out by the Mr./Ms.
……………………………………. Regd.No:……………………………………….. of
2
EXERCISE-1
Module Name: Angular Application Setup Observe the link http://localhost:4200/welcome on which the
mCart application is running. Perform the below activities to understand the features of the application.
REQUIREMENTS DETAILS
You can use the Angular CLI to create projects, generate application and library code, and perform a
variety of ongoing development tasks such as testing, bundling, and deployment.
To install the Angular CLI, open a terminal window and run the following command:
On Windows client computers, the execution of PowerShell scripts is disabled by default. To allow the
execution of PowerShell scripts, which is needed for npm global binaries, you must set the
following execution policy:
3
Carefully read the message displayed after executing the command and follow the instructions. Make sure
you understand the implications of setting an execution policy.
1. Run the CLI command ng new and provide the name my-app, as shown here:
2. The ng new command prompts you for information about features to include in the initial app. Accept
the defaults by pressing the Enter or Return key.
The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a
few minutes.
The CLI creates a new workspace and a simple Welcome app, ready to run.
The Angular CLI includes a server, for you to build and serve your app locally.
my-app
ng serve --open
The ng serve command launches the server, watches your files, and rebuilds the app as you make changes
to those files.
The --open (or just -o) option automatically opens your browser to http://localhost:4200/.
4
Output:
Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more
information, please see https://nodejs.org/en/about/releases/.
5
CREATE my-app/src/app/app-routing.module.ts (245 bytes)
Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more
information, please see https://nodejs.org/en/about/releases/.
? Would you like to share pseudonymous usage data about this project with the Angular Team
Thank you for sharing pseudonymous usage data. Should you change your mind, the following
ng analytics disable
6
Initial Chunk Files | Names | Raw Size
√ Compiled successfully.
7
8
1b. Course Name: Angular JS
Module Name: Components and Modules Create a new component called hello and render Hello
Angular on the page.
Process :
In this step, after you download the default starting app, you build the default Angular app. This confirms
that your development environment has what you need to continue the tutorial.
npm install
ng serve
In this step, you get to know the files that make up a default Angular app.
9
⚫ app.component.ts is the source file that describes the app-root component. This is the top-level Angular
component in the app. A component is the basic building block of an Angular application. The component
description includes the component's code, HTML template, and styles, which can be described in this file,
or in separate files.
In this app, the styles are in a separate file while the component's code and HTML template are in this file.
⚫ app.component.css is the style sheet for this component.
⚫ New components are added to this directory.
⚫ In the file explorer, find the image directory (/assets) that contains images used by the app.
⚫ In the file explorer, find the files and directories that an Angular app needs to build and run, but they are
not files that you normally interact with.
⚫ .angular has files required to build the Angular app.
⚫ .e2e has files used to test the app.
⚫ .node_modules has the node.js packages that the app uses.
⚫ angular.json describes the Angular app to the app building tools.
⚫ package.json is used by npm (the node package manager) to run the finished app.
⚫ tsconfig.* are the files that describe the app's configuration to the TypeScript compiler.
After you have reviewed the files that make up an Angular app project, continue to the next step.
In this step, you update the Angular project files to change the displayed content.
In your IDE:
1. Open first-app/src/index.html.
2. In index.html, replace the <title> element with this code to update the title of the app.
Replace in src/index.html
<title>Homes</title>
5. In app.component.ts, in the AppComponent class definition, replace the title line with this code to
change the component title.
Replace in src/app/app.component.ts
title = 'homes';
10
6. If you stopped the ng serve command from step 1, in the Terminal window of your IDE, run ng
serve again.
7. Open your browser and navigate to localhost:4200 and confirm that the app builds without error and
displays Hello world in the title and body of your app:
Program:
Helloworld.js
Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Default</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
<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/app.component';
bootstrapApplication(AppComponent,
{providers: [provideProtractorTestingSupport()]})
.catch(err => console.error(err));
Style.css:
{
margin: 0;
padding: 0;
}
body {
font-family: 'Be Vietnam Pro', sans-serif;
}
:root {
--primary-color: #605DC8;
--secondary-color: #8B89E6;
--accent-color: #e8e7fa;
--shadow-color: #E8E8E8;
}
button.primary {
padding: 10px;
border: solid 1px var(--primary-color);
background: var(--primary-color);
color: white;
border-radius: 8px;
}
12
App.component.css
:host {
--content-padding: 10px;
header {
display: block;
height: 60px;
padding: var(--content-padding);
.content {
padding: var(--content-padding);
App.component.ts
@Component({
selector: 'app-root',
standalone: true,
imports: [],
template: `<h1>Hello</h1>`,
styleUrls: ['./app.component.css'],
})
title = 'default';
13
Output:
~/projects/qqsjdl--run
❯ npm install --legacy-peer-deps && npm start
npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use
Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-
random for details.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated request@2.88.2: request has been deprecated, see
https://github.com/request/request/issues/3142
npm WARN deprecated protractor@7.0.0: We have news to share - Protractor is deprecated and will reach
end-of-life by Summer 2023. To learn more and find out about other options please refer to this post on
the Angular blog. Thank you for using and contributing to Protractor. https://goo.gle/state-of-e2e-in-
angular
14
main.js | main | 4.11 kB |
✔ Compiled successfully.
✔ Browser application bundle generation complete.
5 unchanged chunks
✔ Compiled successfully.
15
1.c. Course Name: Angular JS Module.
Name: Elements of Template Add an event to the hello component template and when it is clicked, it
should change the course Name.
hello.component.ts:
@Component({
selector: 'app-hello',
templateUrl: "./hello.component.html",
styleUrls: ['./hello.component.css']
})
courseName = "MSD";
constructor() { }
ngOnInit() {
changeName() {
this.courseName = "CSE";
hello.component.html:
<h1>Welcome</h1>
16
hello.component.css:
p{
font-size:20px;
Output:
√ Compiled successfully.
17
18
1.d. Course Name: Angular JS
Module Name: Change Detection
progressively building the PoolCarz application
Change detection is the process through which Angular checks to see whether your application state has
changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top
to bottom, looking for changes. Angular runs its change detection mechanism periodically so that changes
to the data model are reflected in an application’s view. Change detection can be triggered either manually
or through an asynchronous event (for example, a user interaction or an XMLHttpRequest completion).
Change detection is highly optimized and performant, but it can still cause slowdowns if the application
runs it too frequently.
In this guide, you’ll learn how to control and optimize the change detection mechanism by skipping parts
of your application and running change detection only when necessary.
The Angular change detection mechanism is much more transparent and easier to reason about than its
equivalent in AngularJs. But there are still situations (like when doing performance optimizations) when
we really need to know what's going on under the hood. So let's dig deeper into change detection by going
over the following topics:
What happens is that Angular at startup time will patch several low-level browser APIs, such as for
example addEventListener, which is the browser function used to register all browser events, including
click handlers. Angular will replace addEventListener with a new version that does the equivalent of this:
19
function addEventListener(eventName, callback) {
callRealAddEventListener(eventName, function() {
callback(...);
if (changed) {
angular.reRenderUIPart();
});
@Component({
selector: 'todo-item',
(click)="onToggle()">{{todo.owner.firstname}} -
{{todo.description}}
- completed: {{todo.completed}}</span>`
})
@Input()
todo:Todo;
20
@Output()
onToggle() {
this.toggle.emit(this.todo);
Each Angular component has an associated change detector, which is created at application startup time. For
example, take the following
TodoItem component:
Program:
Index.html:
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PoolCarz</title>
<base href="/">
21
Output:
22
EXERCISE-2
A. Module Name: Structural Directives - ngIf Create a login form with username and password fields. If
the user enters the correct credentials, it should render a "Welcome <>" message otherwise it should
render "Invalid Login!!! Please try again..." message
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_auth_01276374022604390425
95_shared?collectionId=lex_2085851554
App.component.html
<div *ngIf="!submitted">
<form>
<label>User Name</label>
<label for="password">Password</label>
</form>
</div>
<div *ngIf="submitted">
</div>
<ng-template #failureMsg>
</ng-template>
</div>
23
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
isAuthenticated!: boolean;
submitted = false;
userName!: string;-
this.submitted = true;
this.userName = name;
this.isAuthenticated = true;
} else {
this.isAuthenticated = false;
App.module.ts
24
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
HttpClientModule],
bootstrap: [AppComponent]
})
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HelloWorld</title>
<base href="/">
25
</head>
<body>
<app-root></app-root>
</body>
</html>
Output:
26
27
28
2b) Course Name: Angular JS Module Name: ngFor Create a courses array and rendering it in the
template using ngFor directive in a list format.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_32795774277593590000_share
d?collectionId=lex_208585155432546000 00_shared&collectionType=Course
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
courses: any[] = [
];
App.component.html
<ul>
{{ i }} - {{ course.name }}
</li>
</ul>
29
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HelloWorld</title>
<base href="/">
</head>
<body>
<app-root></app-root>
</body>
</html>
Output:
30
2c) Course Name: Angular JS Module Name: ngSwitch Display the correct option based on the value passed
to ngSwitch directive.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_23388127475984175000_shared?co
llectionId=lex_208585155432546000 00_shared&collectionType=Course
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
choice = 0;
nextChoice() {
this.choice++;
App.component.html
<h4>
</h4>
31
<div [ngSwitch]="choice">
</div>
<div>
<button (click)="nextChoice()">
Next Choice
</button>
</div>
32
Output:
33
2d) Course Name: Angular JS
Module Name: Custom Structural Directive Create a custom structural directive called 'repeat' which
should repeat the element given a number of times.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_24073319904331424000_share
d?collectionId=lex_208585155432546000 00_shared&collectionType=Course
App.module.ts
@NgModule({
declarations: [
AppComponent,
RepeatDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
34
repeat.directive.ts
@Directive({
selector: '[appRepeat]'
})
this.viewContainer.createEmbeddedView(this.templateRef);
App.component.html
<h3>Structural Directive</h3>
35
Output:
36
EXERCISE-3
3a) Course Name: Angular JS Module Name: Attribute Directives - ngStyle Apply multiple CSS
properties to a paragraph in a component using ngStyle.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_24037156998765367000_share
d?collectionId=lex_208585155432546000 00_shared&collectionType=Course
App.component.html
<p [ngStyle]="{
color:colorName,
'font-weight':fontWeight,
borderBottom: borderStyle
}">
</p>
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
colorName = 'red';
37
fontWeight = 'bold';
App.component.css
p{
font-family: Lato;
App.module.ts
@NgModule({
HttpClientModule],
bootstrap: [AppComponent]
38
})
Output:
39
3b) Course Name: Angular JS
Module Name: ngClass Apply multiple CSS classes to the text using ngClass directive.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_3459610297074182000_shared
?collectionId=lex_2085851554325460000 0_shared&collectionType=Course
App.component.css
.bordered {
background-color: #eee;
.color {
color: blue;
App.component.html
</div>
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
40
export class AppComponent {
isBordered = true;
isColor = true;
Output:
41
3c) Course Name: Angular JS Module Name: Custom Attribute Directive Create an attribute directive
called 'showMessage' which should display the given message in a paragraph when a user clicks on it
and should change the text color to red.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_14783742359773809000_share
d?collectionId=lex_208585155432546000 00_shared&collectionType=Course
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Message.directive.ts
@Directive({
selector: '[appMessage]',
})
42
constructor(private el: ElementRef, private renderer: Renderer2) {
@HostListener('click') onClick() {
this.el.nativeElement.innerHTML = this.message;
App.component.html
<h3>Attribute Directive</h3>
App.component.css
h3 {
color: #369;
font-size: 250%;
p{
color: #ff0080;
43
font-family: Arial, Helvetica, sans-serif;
font-size: 150%;
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
44
Output
45
EXERCISE-4
Module Name: Property Binding Binding image with class property using property binding.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_8951964709153619000_shared
?collectionId=lex_2085851554325460000 0_shared&collectionType=Course
Code:
App.components.ts:
@Component({
selector: 'app-root',
template: `<div>
</div>`
})
ImagePath : string =
"https://upload.wikimedia.org/wikipedia/commons/b/b1/Tata_Consultancy_Services_Logo.svg";
46
Output:
47
4b) Course Name: Angular JS Module Name: Attribute Binding
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
colspanValue = '2';
App.component.html
<table border=1>
<tr>
<td>Second</td>
</tr>
48
<tr>
<td>Third</td>
<td>Fourth</td>
<td>Fifth</td>
</tr>
</table>
Output:
49
4c) Course Name: Angular JS Module Name: Style and Event Binding
Binding an element using inline style and user actions like entering text in input fields.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_7417401021103822000_shared
?collectionId=lex_2085851554325460000 0_shared&collectionType=Course
[style.styleproperty]
Example:
The ngStyle directive is preferred when it is required to set multiple inline styles at the same time.
Event binding
Output:
50
EXERCISE-5
Display the product code in lowercase and product name in uppercase using built-in pipes.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_11810543990912035000_share
d?collectionId=lex_208585155432546000 00_shared&collectionType=Course
uppercase
Syntax:
{{ expression | uppercase }}
Example:
{{ "Laptop" | uppercase }}
Output:
LAPTOP
lowercase
Syntax:
{{ expression | lowercase }}
Example:
{{ "LAPTOP" | lowercase }}
Output:
51
laptop
titlecase
This pipe converts the first character in each word of the given expression into a capital letter.
Syntax:
{{ expression | titlecase }}
Example:
Output:
Product Details
Program:
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
productCode = 'PROD_P001';
productName = 'Laptop';
52
}
App.component.html
<table style="text-align:left">
<tr>
</tr>
<tr>
</tr>
</table>
Output:
53
5b) Course Name: Angular JS Module Name: Passing Parameters to Pipes
A pipe can also have optional parameters to change the output. To pass parameters, after a pipe name add a
colon( : ) followed by the parameter value.
Syntax:
pipename : parametervalue
pipename : parametervalue1:parametervalue2
Below are the built-in pipes present in Angular, which accept optional parameters using which the pipe's
output can be fine-tuned.
currency
This pipe displays a currency symbol before the expression. By default, it displays the currency symbol $
Syntax:
{{ expression | currency:currencyCode:symbol:digitInfo:locale }}
currencyCode is the code to display such as INR for the rupee, EUR for the euro, etc.
symbol is a Boolean value that represents whether to display currency symbol or code.
54
symbol-narrow: displays the narrow symbol of currency. Some countries have two symbols for their
currency, regular and narrow. For example, the Canadian Dollar CAD has the symbol as CA$ and symbol-
narrow as $.
{minIntegerDigits}.{minFractionDigits} - {maxFractionDigits}
minFractionDigits is the minimum number of digits to display after the fraction. The default value is 0
maxFractionDigits is the maximum number of digits to display after the fraction. The default value is 3
locale is used to set the format followed by a country/language. To use a locale, the locale needs to be
registered in the root module.
For Example,to set locale to French (fr), add the below statements in app.module.ts
registerLocaleData(localeFrench);
Examples:
55
date
This pipe can be used to display the date in the required format
Syntax:
{{ expression | date:format:timezone:locale }}
The format indicates in which form the date/time should be displayed. Following are the pre-defined
options for it.
'medium' :equivalent to 'MMM d, y, h:mm:ss a' (e.g. Jan 31, 2018, 11:05:04 AM)
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (e.g. January 31, 2018 at 11:05:04 AM GMT+5)
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (e.g. Wednesday, January 31, 2018 at 11:05:04
AM GMT+05:30)
'fullDate' : equivalent to 'EEEE, MMMM d, y' (e.g. Wednesday, January 31, 2018)
Timezone to be used for formatting. For example, ’+0430’ (4 hours, 30 minutes east of the Greenwich
meridian) If not specified, the local system timezone of the end-user's browser will be used.
56
locale is used to set the format followed by a country/language. To use a locale, register the locale in the
root module.
For Example, to set locale to French (fr), add the below statements in app.module.ts
registerLocaleData(localeFrench);
Examples:
{{ 90000000 | date }} will display Jan 2, 1970 – date pipe will start from Jan 1, 1970 and based on the
given number of milliseconds, it displays the datepercent
Syntax:
{{ expression | percent:digitInfo:locale }}
{minIntegerDigits}.{minFractionDigits} - {maxFractionDigits}
57
minIntegerDigits is the minimum integer digits to display. The default value is 1
minFractionDigits is the minimum number of digits to display after the fraction. The default value is 0.
maxFractionDigits is the maximum number of digits to display after the fraction. The default value is 3.
locale is used to set the format followed by a country/language. To use a locale, register the locale in the
root module.
For Example, to set locale to French (fr), add the below statements in app.module.ts
registerLocaleData(localeFrench);
Examples:
slice
This pipe can be used to extract a subset of elements or characters from an array or string respectively.
Syntax:
58
{{ expression | slice:start:end }}
start represents the starting position in an array or string to extract items. It can be a
positive integer which will extract from the given position till the end
negative integer which will extract the given number of items from the end
end represents the ending position in an array or string for extracting items. It can be
positive number that returns all items before the end index
negative number which returns all items before the end index from the end of the array or string
Examples:
number
59
This pipe can be used to format a number.
Syntax:
{{ expression | number:digitInfo }}
{minIntegerDigits}.{minFractionDigits} - {maxFractionDigits}
minFractionDigits is the minimum number of digits to display after the fraction. The default value is 0.
maxFractionDigits is the maximum number of digits to display after fraction. The default value is 3.
Example:
Program:
App.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
60
styleUrls: ['./app.component.css']
})
productCode = 'PROD_P001';
productPrice = 217021;
purchaseDate = '1/17/2018';
productTax = '0.1';
productRating = 4.92;
App.component.html
<table style="text-align:left">
<tr>
</tr>
<tr>
</tr>
<tr>
61
<th> Product Price </th>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
App.module.ts
registerLocaleData(localeFrench);
@NgModule({
62
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
output:
63
5c) Course Name: Angular JS Module Name: Nested Components Basics
Load CourseslistComponent in the root component when a user clicks on the View courses list button.
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_24231999287700136000_share
d?collectionId=lex_208585155432546000 00_shared&collectionType=Course
64
EXERCISE-6
6.aCourse Name: Angular JS Module Name: Passing data from Container Component to Child Component
Create an AppComponent that displays a dropdown with a list of courses as values in it. Create another
component called the CoursesList component and load it in AppComponent which should display the
course details. When the user selects a course from the
https://infyspringboard.onwingspan.com/web/en/viewer/webmodule/lex_15758356947336235000_shared?
collectionId=lex_208585155432546000 00_shared&collectionType=Course
Program:
<div>
</select>
<app-courses-list [selectedCourse]="selectedCourse"></app-courses-list>
</div>
<div *ngIf="selectedCourse">
<h2>Course Details</h2>
<table>
<tr>
<th>Course Name</th>
65
<th>Instructor</th>
<th>Start Date</th>
</tr>
</table>
</div>
66
6b.Course Name: Angular JS Module Name: Passing data from Child Component to ContainerComponent
Create an AppComponent that loads another component called the CoursesList component. Create another
component called CoursesListComponent which should display the courses list in a table along with a
register .button in each row. When a user clicks on th
app.component.html
<div>
<h1>Welcome to Course Registration App</h1>
<app-courses-list></app-courses-list>
</div>
courses-list.component.html
<table>
<thead>
<tr>
<th>Course Name</th>
<th>Instructor</th>
<th>Start Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<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
@Component({
67
selector: 'app-courses-list',
templateUrl: './courses-list.component.html',
styleUrls: ['./courses-list.component.css']
})
export class CoursesListComponent {
courses = [
{ name: 'Math 101', instructor: 'John Doe', startDate: '2023 -09-15' },
{ name: 'History 202', instructor: 'Jane Smith', startDate: '2023 -09-20' },
{ name: 'Science 303', instructor: 'David Johnson', startDate: '2023 -09-25' },
];
register(course: any) {
alert(`You have registered for ${course.name}`);
}
}
Output:
68
6c.Course Name: Angular JS Module Name: Shadow DOM Apply ShadowDOM and None encapsulation
modes to components.
ShadowDOM:
shadow-dom-example.component.ts
@Component({
selector: 'app-shadow-dom-example',
templateUrl: './shadow-dom-example.component.html',
styleUrls: ['./shadow-dom-example.component.css'],
encapsulation: ViewEncapsulation.ShadowDom })
export class ShadowDomExampleComponent {
title = 'This content is inside the Shadow DOM';
}
shadow-dom-example.component.html
69
None Encapsulation
none-encapsulation-example.component.ts
@Component({
selector: 'app-none-encapsulation-example',
templateUrl: './none-encapsulation-example.component.html',
styleUrls: ['./none-encapsulation-example.component.css'],
encapsulation: ViewEncapsulation.None // Apply None encapsulation mode
})
export class NoneEncapsulationExampleComponent {
title = 'This content is inside the NoneEncapsulation';
}
none-encapsulation-example.component.html
70
71
6d. Course Name: Angular JS Module Name: Component Life Cycle
Override component life-cycle hooks and logging the corresponding messages to understand the flow.
app.component.html:-
<p>hello world</p>
app.component.ts:-
import { Component, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'my-app',
template: '<p>hello preethi</p>' // Add an empty template or a placeholder
})
export class ExampleComponent implements OnChanges {
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges:', changes);
}
}
app.module.ts:-
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [
BrowserModule
],
declarations: [
ExampleComponent
],
bootstrap: [ExampleComponent]
})
export class AppModule { }
72
Output:
Helloworld
73
EXERCISE-7
7 a.)Course Name: Angular JS Module Name: Template Driven Forms Create a courseregistration
form as a template-driven form.
course-registration-form.component.html
<form #courseRegistrationForm="ngForm" (ngSubmit)="submitForm(courseRegistrationFo
rm)">
<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" ngModel required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel required email>
</div>
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" ngModel pattern="[0-
9]*" minlength="10" maxlength="15" required>
</div>
<div class="form-group">
<label for="course">Select a Course:</label>
<select id="course" name="course" ngModel required>
<option value="">Select a course</option>
<option value="course1">Course 1</option>
<option value="course2">Course 2</option>
<option value="course3">Course 3</option>
</select>
</div>
<div class="form-group">
<label for="comments">Comments:</label>
<textarea id="comments" name="comments" ngModel></textarea>
</div>
74
<button type="submit" [disabled]="!courseRegistrationForm.valid">Submit</button>
</form>
course-registration-form.component.ts
@Component({
selector: 'app-course-registration-form',
templateUrl: './course-registration-form.component.html',
styleUrls: ['./course-registration-form.component.css']
})
export class CourseRegistrationFormComponent {
constructor() { }
submitForm(form: any) {
if (form.valid) {
// You can access the form values through the 'form.value' object
console.log('Form submitted with values:', form.value);
// You can send the form data to your server or perform other actions here
} else {
// Handle form validation errors
console.log('Form is invalid. Please check the fields.');
}
}
}
app.component.css
body {
font-family: Arial, sans-serif;
margin: 0;
75
padding: 0;
background-color: #f4f4f4;
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
app.component.html
<div class="container">
<h1>{{ title }}</h1>
<app-course-registration-form></app-course-registration-form>
</div>
app.component.ts
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Course Registration App';
}
76
app.module.ts
@NgModule({
declarations: [
AppComponent,
CourseRegistrationFormComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
77
Output:
78
7b.Course Name: Angular JS
app.component.html:-
<div>
<h2>Employee Registration Form</h2>
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" formControlName="firstName" class="form-
control">
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" formControlName="lastName" class="form-
control">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email" class="form-control">
</div>
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" formControlName="phone" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div class="message">
{{ formMessage }}
</div>
</div>
app.component.ts:-
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
79
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
employeeForm: FormGroup;
formMessage: string = '';
ngOnInit() {
this.employeeForm = this.fb.group({
firstName: [''],
lastName: [''],
email: [''],
phone: ['']
});
}
onSubmit() {
if (this.employeeForm.valid) {
console.log(this.employeeForm.value);
this.formMessage = 'Data submitted successfully!';
this.employeeForm.reset();
} else {
this.formMessage = 'Fill in all details correctly.';
}
}
}
app.module.ts:-
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms'; // Import this line
80
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule, // Add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
81
7c.Course Name: Angular JS
Create a custom validator for an email field in the employee registration form (
reactive form)
Program:
app.component.html:-
<div>
<h2>Employee Registration Form</h2>
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" formControlName="firstName" class="form-
control">
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" formControlName="lastName" class="form-
control">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email" class="form-control">
</div>
<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" formControlName="phone" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div class="message">
{{ formMessage }}
</div>
</div>
82
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']
})
export class AppComponent implements OnInit {
employeeForm: FormGroup;
formMessage: string = '';
ngOnInit() {
this.employeeForm = this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
phone: ['', [Validators.required, Validators.pattern(/^\d{10}$/)]]
});
}
onSubmit() {
if (this.employeeForm.valid) {
this.formMessage = 'Data submitted successfully!';
this.employeeForm.reset();
} else {
this.formMessage = 'Fill in all details correctly.';
}
}
}
app.module.ts:-
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms'; // Import this line
83
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule, // Add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
84
EXERCISE-8
Create a custom validator for the email field in the course registration form.
app.component.html:-
<form [formGroup]="registrationForm">
<!-- Other form fields -->
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" class="form-control" formControlName="email">
app.component.ts:-
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { emailValidator } from './app.module'; // Import the custom validator
@Component({
85
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
registrationForm: FormGroup;
submitted = false; // Add a flag to track form submission
onSubmit() {
this.submitted = true; // Set the flag to true on submit
if (this.registrationForm.valid) {
app.module.ts:-
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ReactiveFormsModule],
86
bootstrap: [AppComponent],
})
export class AppModule {}
return null;
}
Output:
87
8b.Course Name: Angular JS
Create a Book Component which fetches book details like id, name and displays them
on the page in a list format. Store the book details in an array and fetch the data using
a custom service.
Program:
app.component.html:-
<!-- app.component.html -->
<div>
<h1>Welcome to my-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']
})
export class AppComponent {
name = 'Angular ' + VERSION.full;
}
app.module.ts:-
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
88
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent,
BookListComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
book-list.component.html:-
<!-- book-list.component.html -->
<div>
<h2>Book List</h2>
<ul>
<li *ngFor="let book of books">
{{ book.name }}
</li>
</ul>
</div>
book-list.component.ts:-
// book-list.component.ts
@Component({
selector: 'app-book-list',
templateUrl: './book-list.component.html',
styleUrls: ['./book-list.component.css'],
})
export class BookListComponent implements OnInit {
books: { id: number; name: string }[] = [];
89
constructor(private bookService: BookService) {}
ngOnInit(): void {
this.bookService.getBooks().subscribe((books) => {
this.books = books;
});
}
}
book.service.ts:-
// book.service.ts
@Injectable({
providedIn: 'root',
})
export class BookService {
private books: { id: number; name: string }[] = [
{ id: 1, name: 'Book 1' },
{ id: 2, name: 'Book 2' },
{ id: 3, name: 'Book 3' },
];
90
Output:
91
8c.Course Name: Angular JS
Program:
app.module.ts:-
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:-
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
data: string;
92
constructor(private dataService: DataService) {}
ngOnInit(): void {
this.dataService.getData().subscribe((result) => {
this.data = result;
});
}
}
app.component.html:-
<div>
<h1>Welcome to my-app</h1>
<p>Data from Observable:</p>
<p>{{ data }}</p>
</div>
data.service.ts:-
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
getData(): Observable<string> {
const data = 'This is some data from an observable!';
return of(data);
}
}
93
Output:
94
EXERCISE-9
Module Name: Server Communication using HttpClient Create an application for Server
Communication using HttpClient
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com'; // Replace with your server URL
getData(): Observable<any> {
return this.http.get(`${this.apiUrl}/posts/1`); // Replace with your API endpoint
}
}
data-display.component.ts
@Component({
selector: 'app-data-display',
templateUrl: './data-display.component.html',
styleUrls: ['./data-display.component.css']
95
})
export class DataDisplayComponent implements OnInit {
data: any;
ngOnInit(): void {
this.dataService.getData().subscribe(response => {
this.data = response;
});
}
}
Step 5: Create a Component Template
data-display.component.html
<div *ngIf="data">
<h2>Data from the Server:</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
@NgModule({
declarations: [
AppComponent,
DataDisplayComponent
],
imports: [
BrowserModule,
HttpClientModule, // Add HttpClientModule to the imports array
],
providers: [DataService],
bootstrap: [AppComponent]
96
})
export class AppModule { }
Output:
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
Output:
The data received from the server in JSON format. It includes the following fields:
userId : The ID of the user.
Id : The ID of the data entry.
Title : The title of the data entry.
Body : The body or content of the data entry.
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.
97
9b. Course Name: Angular JS
Module Name: Communicating with different backend services using Angular HttpClient Create a
custom service called ProductService in which Http class is used to fetch data stored in the JSON files.
Product-list.component.ts:
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
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';
98
@Injectable({
providedIn: 'root'
})
export class ProductService {
private productsUrl = 'assets/products.json';
getProducts(): Observable<any[]> {
return this.http.get<any[]>(this.productsUrl);
}
}
App.component.html:
<div *ngIf="products.length > 0; else noProducts">
<h2>Products</h2>
<ul>
<li *ngFor="let product of products">
<h3>{{ product.name }}</h3>
<p>Price: {{ product.price }}</p>
<p>Description: {{ product.description }}</p>
</li>
</ul>
</div>
<ng-template #noProducts>
<p>No products available</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[] = [];
ngOnInit() {
99
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';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
100
Exercise - 10
Course Name: Angular JS
Module Name: Routing Basics, Router Links Create multiple components and add routing to provide
navigation between them.
app-routing.module.ts:
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
app.component.html:
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
101
</nav>
<router-outlet> </router-outlet>
app.component.ts:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
app.module.ts:
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent]
})
102
about.component.html:
<p>
mst
</p>
home.component.html:
<p>
</p>
Output:
HomeAbout
Mst
HomeAbout
103
10)b)Module Name:Route Guards
Considering the same example used for routing, add route guard to BooksComponent. Only after
logging in, the user should be able to access BooksComponent. If the user tries to give the URL of
Bookscomponent inanother tab or window, or if the user triesConsidering the same example used
for routing, add route guard to BooksComponent. Only after logging in, the user should be able
to access BooksComponent. If the usertries to give the URL of Bookscomponent in another tab or
window, or if the user tries
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';import Home
from './components/Home';
import About from './components/About'; import Contact
from './components/Contact'; const App = () => {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
};
export default App; import React
from 'react';const Contact = () => {
104
return <div>This is the Contact page.</div>;
};
export default Contact;
105
10)c)Module Name:Asynchronous Routing
Apply lazy loading to BookComponent. If lazy loading is not added to the demo, it has loaded in
1.14 s. Observe the load time at the bottom of the browser console. Press F12 in the browser and
click the Network taband check the Load time
Code:
import React from 'react';const Books = ()
=> {
return <div>This is the Books page. Only logged-in users can accessthis.</div>;
};
export default Books;
import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';import Home from
'./components/Home';
import About from './components/About'; import Contact from
'./components/Contact';
import { login, logout, isAuthenticatedUser } from './authService';const Books =
React.lazy(() => import('./components/Books')); const App = () => {
// ... rest of the code ...return (
<Router>
<div>
<hr />
<Suspense fallback={<div>Loading...</div>}>
<Route path="/books" component={Books} />
</Suspense>
</div>
</Router>
);
};
export default App;
106
10)d)Module Name:Nested Routes Implement Child Routes to
a submoduleCode:
// src/components/BookDetail.jsimport React from
'react';
import { useParams } from 'react-router-dom';const BookDetail = ()
=> {
const { bookId } = useParams();
return <div>Details for Book {bookId}</div>;
};
export default BookDetail;
// src/components/Books.jsimport React
from 'react';
import { Route, Link, useRouteMatch } from 'react-router-dom';import BookDetail
from './BookDetail';
const Books = () => {
const { path, url } = useRouteMatch();return (
<div>
<h2>Books</h2>
<ul>
<li>
<Link to={`${url}/1`}>Book 1</Link>
</li>
<li>
<Link to={`${url}/2`}>Book 2</Link>
</li>
{/* Add more books as needed */}
</ul>
<Route exact path={path}>
<p>Please select a book.</p>
107
</Route>
108
Exercise – 11
11 a. MongoDB Essentials - A Complete MongoDB Guide Module Name:Installing MongoDB on
the local computer, Create MongoDB Atlas Cluster
Installing MongoDB on Local Computer:
109
1. Create a Cluster:
● After signing up and logging in, click the "Build a New Cluster"button.
● Choose a cloud provider, region, and cluster settings. You can choosethe free tier (M0) to get
started.
2. Configure Security:
● Click "Security" in the left-hand menu.
● Add your IP address to the IP Whitelist to allow connections to yourcluster.
3. Connect to Your Cluster:
● Click "Clusters" in the left-hand menu.
● Click the "Connect" button for your cluster.
● Choose "Connect Your Application" to get the connection string.
4. Connect to Atlas Cluster using MongoDB Shell:
● Open a terminal window.
● Run mongo "your_connection_string" to connect to your Atlascluster. Replace
"your_connection_string" with the actual connection string you obtained.
110
11.b. Introduction to the CRUD Operations Write MongoDB queries toperform CRUD
operations on document using insert(), find(), update(),remove().
SOURCE CODE:
methods.
])
// Find documents with a field value matching a rangedb.collectionName.find({ age: { $gt: 25,
$lt: 40 } })
3. Update Documents:
To update documents in a collection, you can use the updateOne() or
111
updateMany() methods.
db.collectionName.updateOne(
{ field: value },
{ field: value },
112
Exercise - 12
12a. Create and Delete Databases and Collections Write MongoDB queries toCreate and drop
databases and collections.
To create a new database, you can use the use command in the MongoDB shell.However, note that a
database isn't actually created until you insert data into it.
// Switch to a new database (creates it if it doesn't exist)use
newDatabaseName
1. Create a Collection:
Collections are created automatically when you insert data into them. However, youcan explicitly
create a collection using the createCollection() method.
2. Drop a Collection:
To drop (delete) a collection, you can use the drop() method.
3. Drop a Database:
To drop a database, you can use the dropDatabase() method. Make sure to switchto the appropriate
database before using this command.
// Drop the current database (make sure you're in the right database)db.dropDatabase().
113
12b. Create and Delete Databases and Collections
Write MongoDB queries to Create and drop databases and collections.SOURCE CODE:
find(): The find() method retrieves documents from a collection that match aspecified query.
You can use various query operators to filter the results.
// Find documents with a field value matching a rangedb.collectionName.find({ age: { $gt: 25,
$lt: 40 } })\
limit(): The limit() method restricts the number of documents returned by a query.
sort(): The sort() method arranges the documents in a specific order based on oneor more fields.
createIndex(): The createIndex() method creates an index on specified fields in acollection, which can
improve query performance.
aggregate(): The aggregate() method performs advanced data processing using apipeline of stages. It's
useful for complex querying and transformations.
114
// Example aggregation pipeline: calculate average age by genderdb.collectionName.aggregate([
115