0% found this document useful (0 votes)
17 views91 pages

Angular JS Course: Application Setup Guide

lab manual

Uploaded by

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

Angular JS Course: Application Setup Guide

lab manual

Uploaded by

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

YJRDMS COLLEGE OF ENGINEERING

[Link]

1.a Course Name: Angular JS


Module Name: Angular Application Setup
Observe the link [Link] on which the mCart application is
running. Perform the below activities to understand the features of the application.

Click on the Login button at the top right corner and observe the URL.

2. Login with different credentials (other than admin, admin) and see the message displayed.

3. Login with credentials (admin, admin) and check how the redirection is happening by observing the
URL.

4. Click on the two tabs (Tablets, Mobiles) which display tablet and mobile devices, respectively.

5. Click on any product name and see the product detail page getting displayed.

6. Click on Add to Cart button and add multiple products to the cart (selection count and the total price will be
displayed on the second navigation bar).

7. Click on the cart link on the second navigation bar and observe the cart page which displays the selected
products.

8. Click on the Checkout button and observe the page displayed. Click the Back button and observe the
navigation.

9. Click on the sort dropdown and observe sort functionality based on the options mentioned.

10. Click on the filter dropdown and observe filtering functionality based on the options mentioned.

11. In the search text box placed on the second navigation bar, type the manufacturer name like Samsung,
Apple, etc., and observe the search functionality.

12. Click on the Logout button at the top right corner and observe the redirection happening.

1
YJRDMS COLLEGE OF ENGINEERING

1. InCourse
1.b Name:
the same MyAppAngular JS
application created earlier, create a new component called hello using the
following
Module Name:CLI command
Components and Modules
Create a newng
D:\MyApp> component
generate called hello and
component render Hello Angular on the page
hello
2. This command will create a new folder with the name hello with the following files placed
inside it
3. 3. Open [Link] file and create a property called courseName of type string and
initialize it to "Angular" as shown below
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './[Link]', styleUrls:
['./[Link]']})
export class HelloComponent implements OnInit { courseName: string =
"Angular";
constructor() { }
ngOnInit() {
}
}

4. Open [Link] and display the courseName as shown below in Line 2


<p>
Hello {{ courseName }}
</p>
5. Open [Link] and add the following styles for the paragraph element p
{
color:blue; font-
size:20px;
}
6. Open [Link] file and add HelloComponent to bootstrap property as shown below in Line 11 to
load it for execution
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './[Link]';
import { AppComponent } from './[Link]';
import { HelloComponent } from './hello/[Link]';
@NgModule({
imports: [BrowserModule,AppRoutingModule], declarations:
[AppComponent, HelloComponent], providers: [],
bootstrap: [HelloComponent]
})
export class AppModule { }
7. Open [Link] and load the hello component by using its selector name i.e., app-hello as shown
below in Line 11
8. <!doctype html>
9. <html lang="en">
10. <head>
11. <meta charset="utf-8">
2
YJRDMS COLLEGE OF ENGINEERING

12. <title>MyApp</title>
13. <base href="/">
14. <meta name="viewport" content="width=device-width, initial-scale=1">
15. <link rel="icon" type="image/x-icon" href="[Link]">
16. </head>
17. <body>
18. <app-hello></app-hello>
19. </body>
20. </html>
8. Now run the application by giving the following command D:\
MyApp>ng serve –open

Output:

3
YJRDMS COLLEGE OF ENGINEERING

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 courseName.

1. Open [Link], add a method called changeName() as shown below in Line 12-14. Also, use
external template [Link].
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: "./[Link]",
styleUrls: ['./[Link]']
})
export class HelloComponent implements OnInit
{ courseName = "Angular";
constructor() { }
ngOnInit() {
}
changeName() {
[Link] = "TypeScript";
}
}
2. Open [Link] and add a paragraph and bind it with changeName() method as shown in
Line 3
<h1>Welcome</h1>
<h2>Course Name: {{ courseName }}</h2>
<p (click)="changeName()">Click here to change</p>
3. Save the files and check the output in the browser.

Output:

4
YJRDMS COLLEGE OF ENGINEERING

1.d Course Name: Angular JS


Module Name: Change Detection
progressively building the PoolCarz application

Problem Statement:
You will be progressively building the PoolCarz application throughout this course.
PoolCarz is a web application for carpooling. The application allows users to share rides with others. Users can
either book a ride or offer a ride.
Use Cases:
Login Book a
ride Ride
details Offer
Ride Logout
1. Login: Login to the application to view ride details

2. Book a ride: Renders the rides available and also allows to filter the details based on the start/endpoint of
the rides.

5
YJRDMS COLLEGE OF ENGINEERING

3. Ride Details: When a user selects a particular ride, it renders complete details about that ride and allows
the user to book that ride.

4. Offer Ride: This allows the user to re

gister their
details to offer a ride to others.

6
YJRDMS COLLEGE OF ENGINEERING

2.a Course Name: Angular JS


Module Name: Structural Directives - ngIf
Create a login form with username and password fields. If the user enters the correct
credentials, it should render a "Welcome <<username>>" message otherwise it should
render "Invalid Login!!! Please try again..." message

1. Open [Link] and write the following code:


import { Component } from '@angular/core';
@Component({ selecto
r: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent
{ isAuthenticated!: boolean;
submitted = false; userName!:
string;
onSubmit(name: string, password: string) { [Link]
= true;
[Link] = name;
if (name === 'admin' && password === 'admin')
{ [Link] = true;
} else {
[Link] = false;
}
}
}
2. Write the below-given code in [Link]
<div *ngIf="!submitted">
<form>
<label>User Name</label>
<input type="text" #username /><br /><br />
<label for="password">Password</label>
<input type="password" name="password" #password /><br />
</form>
<button (click)="onSubmit([Link], [Link])">Login</button>
</div>
<div *ngIf="submitted">
<div *ngIf="isAuthenticated; else failureMsg">
<h4>Welcome {{ userName }}</h4>
</div>
<ng-template #failureMsg>
<h4>Invalid Login !!! Please try again...</h4>
</ng-template>
<button type="button" (click)="submitted = false">Back</button></div>

7
YJRDMS COLLEGE OF ENGINEERING

3. Add AppComponent to the bootstrap property in the root module file i.e., [Link]
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './[Link]';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
4. Ensure the [Link] displays app-root.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-root></app-root>
</body>
</html>
5. Save the files and check the output in the browser.

Output:

8
YJRDMS COLLEGE OF ENGINEERING

2.b Course Name: Angular JS


Module Name: ngFor
Create a courses array and rendering it in the template using ngFor directive in a list
format.

1. Write the below-given code in [Link]


import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent
{ courses: any[] = [
{ id: 1, name: 'TypeScript' },
{ id: 2, name: 'Angular' },
{ id: 3, name: 'Node JS' },
{ id: 1, name: 'TypeScript' }
];
}
2. Write the below-given code in [Link]
<ul>
<li *ngFor="let course of courses; let i = index">
{{ i }} - {{ [Link] }}
</li>
</ul>
3. Save the files and check the output in the browser

Output:

9
YJRDMS COLLEGE OF ENGINEERING

2.c Course Name: Angular JS


Module Name: ngSwitch
Display the correct option based on the value passed to ngSwitch directive.

1. Write the below-given code in [Link]


import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent { choice
= 0;
nextChoice() {
[Link]++;
}
}
2. Write the below-given code in [Link]
<h4>
Current choice is {{ choice }}
</h4>
<div [ngSwitch]="choice">
<p *ngSwitchCase="1">First Choice</p>
<p *ngSwitchCase="2">Second Choice</p>
<p *ngSwitchCase="3">Third Choice</p>
<p *ngSwitchCase="2">Second Choice Again</p>
<p *ngSwitchDefault>Default Choice</p>
</div>
<div>
<button (click)="nextChoice()">
Next Choice
</button>
</div>
3. Save the files and check the output in the browser

Output:

10
YJRDMS COLLEGE OF ENGINEERING

2.d Course Name: Angular JS


Module Name: Custom Structural Directive
Create a custom structural directive called 'repeat' which should repeat the element
given a number of times.

To create a custom structural directive, create a class annotated with @Directive


@Directive({
})
class MyDirective{}
Generate a directive called 'repeat' using the following command D:\MyApp>ng
generate directive repeat

It also adds repeat directive to the root module i.e., [Link] to make it available to the entire
module as shown below in Line 7
...
import { RepeatDirective } from './[Link]';
@NgModule({
declarations: [
AppComponent,
RepeatDirective
],
...
})
export class AppModule { }

Open [Link] file and add the following code


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

11
YJRDMS COLLEGE OF ENGINEERING

[Link]

<h3>Structural Directive</h3>
<p *appRepeat="5">I am being repeated...</p>

Output:

12
YJRDMS COLLEGE OF ENGINEERING

3.a Course Name: Angular JS


Module Name: Attribute Directives - ngStyle
Apply multiple CSS properties to a paragraph in a component using ngStyle.

1. Write the below-given code in [Link]

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


@Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent
{ colorName = 'red'; fontWeight
= 'bold';
borderStyle = '1px solid black';
}
2. Write the below-given code in [Link]
<p [ngStyle]="{
color:colorName,
'font-weight':fontWeight,
borderBottom: borderStyle
}">
Demo for attribute directive ngStyle
</p>

Output:

13
YJRDMS COLLEGE OF ENGINEERING

3.b Course Name: Angular JS


Module Name: ngClass
Apply multiple CSS classes to the text using ngClass directive.

1. Write the below-given code in [Link]


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

2. Write the below-given code in [Link]


<div [ngClass]="{bordered: isBordered}">
Border {{ isBordered ? "ON" : "OFF" }}
</div>
3. In [Link], add the following CSS class
.bordered {
border: 1px dashed black;
background-color: #eee;
}

Outpu

14
YJRDMS COLLEGE OF ENGINEERING

3.c 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.

To create a custom attribute directive, we need to create a class annotated with


@Directive
@Directive({
})
class MyDirective { }

Generate a directive called 'message' using the following command D:\


MyApp> ng generate directive message

It also adds message directive to the root module i.e., [Link] to make it available
to the entire module as shown below
...
import { MessageDirective } from './[Link]';
@NgModule({
declarations: [
AppComponent,
MessageDirective
],
...
})
export class AppModule { }

Open the [Link] file and add the following code:


import { Directive, ElementRef, Renderer2, HostListener, Input } from
'@angular/core';
@Directive({
selector: '[appMessage]',
})
export class MessageDirective
{ @Input('appMessage') message!: string;
constructor(private el: ElementRef, private renderer: Renderer2)
{ [Link]([Link], 'cursor', 'pointer');
}
@HostListener('click') onClick()
{ [Link] = [Link];
[Link]([Link], 'color', 'red');
}
}
15
YJRDMS COLLEGE OF ENGINEERING

[Link]

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


@Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
myMessage="Hello, I am from attribute directive"
}

[Link]
<h3>Attribute Directive</h3>
<p [appMessage]="myMessage">Click Here</p>

Add the following CSS styles to the [Link] file h3


{
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
p{
color: #ff0080;
font-family: Arial, Helvetica, sans-serif;
font-size: 150%;}

Output:

16
YJRDMS COLLEGE OF ENGINEERING

4.a Course Name: Angular JS


Module Name: Property Binding
Binding image with class property using property binding.

1. Write the following code in [Link] as shown below import { Component }


from '@angular/core';
@Component({ selector: 'app-root',
templateUrl: './[Link]', styleUrls: ['./[Link]']
})
export class AppComponent { imgUrl = 'assets/imgs/[Link]';
}
2. Write the following code in [Link] as shown below
<img [src]='imgUrl'>
3. Save the files and check the output in the browser

Output:

17
YJRDMS COLLEGE OF ENGINEERING

4.b Course Name: Angular JS


Module Name: Attribute Binding
Binding colspan attribute of a table element to the class property.

1. Write the below-given code in [Link]


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

2. Write the below-given code in [Link]


<table border=1>
<tr>
<td [[Link]]="colspanValue"> First </td>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
<td>Fourth</td>
<td>Fifth</td>
</tr>
</table>
3. Save the files and check the output in the browser

18
YJRDMS COLLEGE OF ENGINEERING

4.c 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.

1. Write the below-given code in [Link]


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

}
2. Write the below-given code in [Link]
<input type="text" [(ngModel)]="name"> <br/>
<div>Hello , {{ name }}</div>
3. Write the below-given code in [Link]
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from
'@angular/core';
import { FormsModule } from '@angular/forms'; import { AppComponent }
from './[Link]'; @NgModule({
declarations: [ AppComponent
],
imports: [ BrowserModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
4. Save the files and check the output in the browser

19
YJRDMS COLLEGE OF ENGINEERING

5.a Course Name: Angular JS


Module Name: Built in Pipes
Display the product code in lowercase and product name in uppercase using built-in
pipes.

1. Write the below-given code in [Link]


import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent { title =
'product details'; productCode =
'PROD_P001'; productName =
'Laptop';
}
2. Write the below-given code in [Link]
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<th> Product Code </th>
<td> {{ productCode | lowercase }} </td>
</tr>
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
</table>
3. Save the files and check the output in the browser.

Output:

20
YJRDMS COLLEGE OF ENGINEERING

5.b Course Name: Angular JS


Module Name: Passing Parameters to Pipes
Apply built-in pipes with parameters to display product details.

1. Write the below-given code in [Link]


import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent { title
= 'product details'; productCode =
'PROD_P001';
productName = 'Apple MPTT2 MacBook Pro';
productPrice = 217021;
purchaseDate = '1/17/2018';
productTax = '0.1';
productRating = 4.92;
}
2. Write the below-given code in [Link]
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<th> Product Code </th>
<td> {{ productCode | slice:5:9 }} </td>
</tr>
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
<tr>
<th> Product Price </th>
<td> {{ productPrice | currency: 'INR':'symbol':'':'fr' }} </td>
</tr>
<tr>
<th> Purchase Date </th>
<td> {{ purchaseDate | date:'fullDate' | lowercase}} </td>
</tr>
<tr>
<th> Product Tax </th>
<td> {{ productTax | percent : '.2' }} </td>
</tr>
<tr>
<th> Product Rating </th>
<td>{{ productRating | number:'1.3-5'}} </td>
</tr>
21
YJRDMS COLLEGE OF ENGINEERING

</table>
3. Write the below-given code in [Link]
import { BrowserModule } from '@angular/platform-browser'; import {
NgModule } from '@angular/core';
import { AppComponent } from './[Link]';

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


import localeFrench from '@angular/common/locales/fr';
registerLocaleData(localeFrench);
@NgModule({ declarati
ons: [ AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

4. Save the files and check the output in the browser

Output:

22
YJRDMS COLLEGE OF ENGINEERING

5.c 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.

1. Create a component called coursesList using the following CLI command


D:\MyApp>ng generate component coursesList

The above command will create a folder with name courses-list with the following files
 [Link]
 [Link]
 [Link]
 [Link]

2. CoursesListComponent class will be added in the [Link] file


import { BrowserModule } from '@angular/platform-browser'; import {
NgModule } from '@angular/core';
import { AppComponent } from './[Link]';
import { CoursesListComponent } from './courses-list/[Link]';
@NgModule({
declarations: [
AppComponent,
CoursesListComponent],
imports: [ BrowserModule
],
providers: [],
bootstrap: [AppComponent]})
export class AppModule { }

3. Write the below-given code in [Link]


import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class CoursesListComponent
{ courses = [
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
}

4. Write the below-given code in [Link]


<table border="1">
23
YJRDMS COLLEGE OF ENGINEERING

<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</tbody>
</table>
5. Add the following code in [Link]
tr{
text-align:cente;}

6. Write the below-given code in [Link]


<h2>Popular Courses</h2>
<button (click)="show = true">View Courses list</button><br /><br />
<div *ngIf="show">
<app-courses-list></app-courses-list>

</div>
7. Write the below-given code in [Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent { show!:
boolean;
}
8. Save the files and check the output in the browser
Output:

24
YJRDMS COLLEGE OF ENGINEERING

6.a Course 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

1. Open the [Link] file created in the example of nested components and
add the following code
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class CoursesListComponent
{ courses = [
{ courseId: 1, courseName: 'Node JS' },
{ courseId: 2, courseName: 'Typescript' },
{ courseId: 3, courseName: 'Angular' },
{ courseId: 4, courseName: 'React JS' },
];
course!: any[];
@Input() set cName(name: string) {

[Link] = [];
for (var i = 0; i < [Link]; i++) { if
([Link][i].courseName === name) {
[Link]([Link][i]);
}
}
}
}
2. Open [Link] and add the following code
<table border="1" *ngIf="[Link] > 0">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of course">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
25
YJRDMS COLLEGE OF ENGINEERING

</tbody>
</table>
3. Add the following in [Link]
<h2>Course Details</h2>
Select a course to view
<select #course (change)="name = [Link]">
<option value="Node JS">Node JS</option>
<option value="Typescript">Typescript</option>
<option value="Angular">Angular</option>
<option value="React JS">React JS</option></select><br /><br />
<app-courses-list [cName]="name"></app-courses-list>
4. Add the following in [Link] import
{ Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./[Link]'],
templateUrl: './[Link]'
})
export class AppComponent
{ name!: string;
}

Output:

26
YJRDMS COLLEGE OF ENGINEERING

6.b 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

[Link]
...
export class CoursesListComponent {
@Output() onRegister = new EventEmitter<string>();
...
register(courseName: string) {
[Link](courseName);
}
}

[Link]
<table border="1">
...
<tbody>
<tr *ngFor="let course of courses">
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td><button (click)="register([Link])">Register</button></td>
</tr>
</tbody>
</table>

[Link]
<h2> Courses List </h2>
<app-courses-list (OnRegister)="courseReg($event)"></app-courses-list>
<br/><br/>
<div *ngIf="message">{{message}}</div>
[Link]
...
export class AppComponent {

27
YJRDMS COLLEGE OF ENGINEERING

message!: string; courseReg(courseName:


string) {
[Link] = `Your registration for ${courseName} is successful`;
}
}
Output:

28
YJRDMS COLLEGE OF ENGINEERING

6.c Course Name: Angular JS


Module Name: Shadow DOM
Apply ShadowDOM and None encapsulation modes to components.

Set ViewEncapsulation to none mode in [Link] file import {


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

Set ViewEncapsulation to none mode in [Link] file


import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-second',
templateUrl: './[Link]', styleUrls:
['./[Link]'], encapsulation:
[Link]
})
export class SecondComponent {
}

Output:

29
YJRDMS COLLEGE OF ENGINEERING

6.d Course Name: Angular JS


Module Name: Component Life Cycle
Override component life-cycle hooks and logging the corresponding messages to understand the flow.

[Link]

import {
Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./[Link]'],
templateUrl: './[Link]'
})
export class AppComponent implements OnInit, DoCheck,
AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy {
data = 'Angular';
ngOnInit() {
[Link]('Init');
}
ngDoCheck(): void { [Link]('Change
detected');
}
ngAfterContentInit(): void
{ [Link]('After content init');
}
ngAfterContentChecked(): void
{ [Link]('After content checked');
}
ngAfterViewInit(): void
{ [Link]('After view init');
}
ngAfterViewChecked(): void
{ [Link]('After view checked');
}
ngOnDestroy(): void {
[Link]('Destroy');
}
}

[Link]
30
YJRDMS COLLEGE OF ENGINEERING

<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]='data'>
<app-child [title]='data'></app-child>
</div>

[Link]

...
export class ChildComponent implements OnChanges { @Input()
title: string = 'I\'m a nested component'; ngOnChanges(changes:
any): void {
[Link]('changes in child:' + [Link](changes));
}
}

Output:

31
YJRDMS COLLEGE OF ENGINEERING

7.a Course Name: Angular JS


Module Name: Template Driven Forms
Create a course registration form as a template-driven form.

Add the following code in the [Link] file

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


import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class RegistrationFormComponent implements OnInit
{ registerForm!: FormGroup;
submitted!: boolean;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
[Link] =
[Link]({ firstName: ['',
[Link]], lastName: ['',
[Link]],
address:
[Link]({ street: [],
zip: [],
city: []
})
});
}
}
[Link]
<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName" />
<div *ngIf="[Link]" class="alert alert-danger"> Firstname
field is invalid.
<p *ngIf="[Link]?.required">
This field is required!
</p>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName" />
32
YJRDMS COLLEGE OF ENGINEERING

<div *ngIf="[Link]. [Link]" class="alert alert-danger"> Lastname


field is invalid.
<p *ngIf="[Link]. [Link]?.required">
This field is required!

</div>
<div class="form-group">
<fieldset formGroupName="address">
<label>Street</label>
<input type="text" class="form-control" formControlName="street" />
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip" />
<label>City</label>
<input type="text" class="form-control" formControlName="city" />
</fieldset>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted = true">
Submit
</button>
</form>
<br/>
<div [hidden]="!submitted">
<h3>Employee Details</h3>
<p>First Name: {{ [Link] }}</p>
<p>Last Name: {{ [Link] }}</p>
<p>Street: {{ [Link] }}</p>
<p>Zip: {{ [Link] }}</p>
<p>City: {{ [Link] }}</p>
</div>
</div>
Output:

33
YJRDMS COLLEGE OF ENGINEERING

7.b Course Name: Angular JS


Module Name: Model Driven Forms or Reactive Forms
Create an employee registration form as a reactive form.

1. Write the below-given code in [Link]

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


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

2. Create a component called RegistrationForm using the following CLI command ng

generate component RegistrationForm

3. Add the following code in the [Link] file

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


import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class RegistrationFormComponent implements OnInit
{ registerForm!: FormGroup;
submitted!:boolean;

constructor(private formBuilder: FormBuilder) { }


ngOnInit() {
[Link] =
[Link]({ firstName: [''”]
34
YJRDMS COLLEGE OF ENGINEERING

address: [Link]({ street:


[],
zip: [],
city: []
})
});
}
}

4. Write the below-given code in [Link]

<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName">
<div *ngIf="[Link]['firstName'].errors" class="alert alert-danger">
Firstname field is invalid.
<p *ngIf="[Link]['firstName'].errors?.['required']"> This
field is required!
</p>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName">
<div *ngIf="[Link]['lastName'].errors" class="alert alert-danger"> Lastname
field is invalid.
<p *ngIf="[Link]['lastName'].errors?.['required']"> This
field is required!
</p>
</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</fieldset>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted=true">Submit</button>
35
YJRDMS COLLEGE OF ENGINEERING

</form>
<br/>
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p>First Name: {{ [Link]('firstName')?.value }} </p>

<p> Last Name: {{ [Link]('lastName')?.value }} </p>


<p> Street: {{ [Link]('[Link]')?.value }}</p>
<p> Zip: {{ [Link]('[Link]')?.value }} </p>
<p> City: {{ [Link]('[Link]')?.value }}</p>
</div>
</div>

5. Write the below-given code in [Link]

.ng-valid[required] {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}

6. Write the below-given code in [Link]

<app-registration-form></app-registration-form>

Output:

36
YJRDMS COLLEGE OF ENGINEERING

7.c Course Name: Angular JS


Module Name: Custom Validators in Reactive Forms
Create a custom validator for an email field in the employee registration form
( reactive form)

1. Write a separate function in [Link] for custom validation as shown below.

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


import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class RegistrationFormComponent implements OnInit
{ registerForm!: FormGroup;
submitted!: boolean;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
[Link] =
[Link]({ firstName: ['',
[Link]], lastName: ['',
[Link]],
address:
[Link]({ street: [],
zip: [],
city: []
}),
email: ['', [[Link],validateEmail]]
});
}
}

function validateEmail(c: FormControl): any {


let EMAIL_REGEXP = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
return EMAIL_REGEXP.test([Link]) ? null :
{ emailInvalid: {
message: "Invalid Format!"
}
};
}

2. Add HTML controls for the email field in the [Link] file as shown below
<div class="container">
<h1>Registration Form</h1>
37
YJRDMS COLLEGE OF ENGINEERING

<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName" />
<p *ngIf="[Link]?.required"> This field is required!
</p>
</div>

</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName" />
<div *ngIf="[Link]" class="alert alert-danger">
Lastname field is invaliddd.
<p *ngIf="[Link]?.required">
This field is required!
</p>
</div>

</div>
<div class="form-group">
<fieldset formGroupName="address">
<label>Street</label>
<input type="text" class="form-control" formControlName="street" />
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip" />
<label>City</label>
<input type="text" class="form-control" formControlName="city" />
</fieldset>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" formControlName="email" />
<div *ngIf="[Link]" class="alert alert-danger"> Email
field is invalid.
<p *ngIf="[Link]?.required">
This field is required!
</p>
<p *ngIf="[Link]?.emailInvalid">
{{ [Link]?.[Link] }}
</p>
</div>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted = true">
Submit
</button>
</form>
38
YJRDMS COLLEGE OF ENGINEERING

<br/>
<div [hidden]="!submitted">
<h3>Employee Details</h3>
<p>First Name: {{ [Link] }}</p>
<p>Last Name: {{ [Link] }}</p>
<p>Street: {{ [Link] }}</p>
<p>Zip: {{ [Link] }}</p>

<p>City: {{ [Link] }}</p>


<p>Email: {{ [Link] }}</p>
</div>
</div>
4. Save the files and check the output in the browser

Output:

39
YJRDMS COLLEGE OF ENGINEERING

8.a Course Name: Angular JS


Module Name: Custom Validators in Template Driven forms
Create a custom validator for the email field in the course registration form.

The code inside [Link] is present under the login folder. Observe the creation of
LoginComponent as a reactive form and addition of validations to it.

<!-- Login form-->


<div class="container container-styles">
<div class="col-xs-7 col-xs-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-body padding">
<form class="form-horizontal" [formGroup]="loginForm">
<div class="form-group" >
<label for="name" class="col-xs-4 control-label" style="text-
align:left">User Name</label>
<div class="col-xs-8">
<input type="text" class="form-control"
[ngClass]="{'valid':[Link]['userName'].valid, 'invalid':[Link]['userName'].invalid
&& ![Link]['userName'].pristine}" formControlName="userName">
<div *ngIf="[Link]['password'].errors &&
[Link]['userName'].dirty">
<div
*ngIf="[Link]['userName'].errors?.['required']" style="color:red">UserName is required
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-xs-4 control-label"
style="text-align:left">Password</label>
<div class="col-xs-8">
<input type="password" class="form-control"
[ngClass]="{'valid':[Link]['password'].valid, 'invalid':[Link]['password'].invalid
&& ![Link]['password'].pristine}" formControlName="password">
<div *ngIf="[Link]['password'].errors &&
[Link]['password'].dirty">
<div
*ngIf="[Link]['password'].errors?.['required']" style="color:red">Password is required
</div>
</div>
</div>
</div>
40
YJRDMS COLLEGE OF ENGINEERING

again...</div>
<div *ngIf="!valid" class="error">Invalid Credentials...Please try

<br />
<div class="form-group">
<span class="col-xs-4"></span>

<div class="col-xs-3">
<button (click)="onSubmit()" class="btn btn-primary"
[disabled]="![Link]">Login</button>
</div>
<span class="col-xs-5" style="top:8px">
<a [routerLink]="['/welcome']"
style="color:#337ab7;text-decoration: underline;">Cancel</a>
</span>
</div>
</form>

41
YJRDMS COLLEGE OF ENGINEERING

Observe the creation of model-driven form within the LoginComponent. Open [Link]. import {

Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core';


import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import {
Router } from '@angular/router';
import { Login } from './Login';
import { LoginService } from './[Link]';
@Component({
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class LoginComponent implements OnInit
{ login = new Login();
users: Login[] = []; valid
= true;
@ViewChild('uname') usernameElement!: ElementRef;
loginForm!: FormGroup;
constructor(private router: Router, private formBuilder: FormBuilder, private
loginService: LoginService, private renderer: Renderer2) {
}
ngOnInit() {
// Makes a service call to fetch users data from the backend
[Link]().subscribe({next:users => [Link] = users});
[Link] = [Link]({
userName: [[Link], [Link]],
password: [[Link], [Link]]
})
}
// Invoked when user clicks submit in login form
// Validates the credentials with the data fetched from the backend
onSubmit() {

//fetches the form object containing the values of all the form controls
[Link] = [Link]();
const user = [Link](currUser => [Link] === [Link] &&
[Link] === [Link])[0];
if (user) {
[Link] = [Link];
[Link](['/products']);
} else {
[Link] = false;
}
}
}

42
YJRDMS COLLEGE OF ENGINEERING

Outpu

43
YJRDMS COLLEGE OF ENGINEERING

8.b Course Name: Angular JS


Module Name: Services Basics
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.

1. Create BookComponent by using the following CLI command


D:\MyApp>ng generate component book
2. Create a file with the name [Link] under the book folder and add the following code.

export class Book


{ id!: number;
name!: string;
}
3. Create a file with the name [Link] under the book folder and add the following code.

import { Book } from './book';


export let BOOKS: Book[] = [
{ id: 1, name: 'HTML 5' },
{ id: 2, name: 'CSS 3' },
{ id: 3, name: 'Java Script' },
{ id: 4, name: 'Ajax Programming' },
{ id: 5, name: 'jQuery' },
{ id: 6, name: 'Mastering [Link]' },
{ id: 7, name: 'Angular JS 1.x' },
{ id: 8, name: 'ng-book 2' },
{ id: 9, name: 'Backbone JS' },
{ id: 10, name: 'Yeoman' }
];

4. Create a service called BookService under the book folder using the following CLI command

D:\MyApp\src\app\book>ng generate service book

5. Add the following code in [Link]

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


BOOKS } from './books-data'; @Injectable({
providedIn: 'root'
})
export class BookService
{ getBooks() {
return BOOKS;
}
}
44
YJRDMS COLLEGE OF ENGINEERING

6. Add the following code in the [Link] file

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


import { Book } from './book';
import { BookService } from './[Link]';
@Component({
selector: 'app-book',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class BookComponent implements OnInit
{ books!: Book[];
constructor(private bookService: BookService) { }
getBooks() {
[Link] = [Link]();
}
ngOnInit() {
7. Create a file with the name [Link] under the book folder and add the following code.

import { Book } from './book';


export let BOOKS: Book[] = [
{ id: 1, name: 'HTML 5' },
{ id: 2, name: 'CSS 3' },
{ id: 3, name: 'Java Script' },
{ id: 4, name: 'Ajax Programming' },
{ id: 5, name: 'jQuery' },
{ id: 6, name: 'Mastering [Link]' },
{ id: 7, name: 'Angular JS 1.x' },
{ id: 8, name: 'ng-book 2' },
{ id: 9, name: 'Backbone JS' },
{ id: 10, name: 'Yeoman' }
];

8. Create a service called BookService under the book folder using the following CLI command

D:\MyApp\src\app\book>ng generate service book

9. Add the following code in [Link]

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


BOOKS } from './books-data'; @Injectable({
providedIn: 'root'
})
export class BookService
{ getBooks() {
45
YJRDMS COLLEGE OF ENGINEERING

return BOOKS;
}
}

10. Add the following code in the [Link] file

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


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

[Link]();
}
}

11. Write the below-given code in [Link]


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

12. Add the following code in [Link] which has styles for books

.books {
margin: 0 0 2em 0; list-
style-type: none;
padding: 0;
width: 13em;
}
.books li { cursor:
pointer;
position: relative; left:
46
YJRDMS COLLEGE OF ENGINEERING

0;
background-color: #eee;
margin: 0.5em; padding:
0.3em 0; height: 1.5em;
border-radius: 4px;
}
.books li:hover
{ color: #607d8b;
background-color: #ddd;
left: 0.1em;
}
.books .badge { display:
inline-block; font-size:
small; color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607d8b; line-
height: 0.5em;
position: relative; left:
-1px;
top: -4px; height:
1.8em;
margin-right: 0.8em; border-
radius: 4px 0 0 4px;
}

13. Add the following code in [Link]

<app-book></app-book>
Output:

47
YJRDMS COLLEGE OF ENGINEERING

8.c Course Name: Angular JS


Module Name: RxJS Observables
Create and use an observable in Angular.

[Link]

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


{ Observable } from 'rxjs'; @Component({
selector: 'app-root',
styleUrls: ['./[Link]'],
templateUrl: './[Link]'
})
export class AppComponent
{ data!: Observable<number>;
myArray: number[] = []; errors!:
boolean;
finished!: boolean;
fetchData(): void {
[Link] = new Observable(observer => { setTimeout(()
=> { [Link](11); }, 1000),
setTimeout(() => { [Link](22); }, 2000),
setTimeout(() => { [Link](); }, 3000);
});
[Link]((value) => [Link](value), error
=> [Link] = true,
() => [Link] = true);
}
}
[Link]<b> Using Observables!</b>
<h6 style="margin-bottom: 0">VALUES:</h6>
<div *ngFor="let value of myArray">{{ value }}</div>
<div style="margin-bottom: 0">ERRORS: {{ errors }}</div>
<div style="margin-bottom: 0">FINISHED: {{ finished }}</div>
<button style="margin-top: 2rem" (click)="fetchData()">Fetch Data</button>

Output:

48
YJRDMS COLLEGE OF ENGINEERING

9.a Course Name: Angular JS


Module Name: Server Communication using HttpClient
Create an application for Server Communication using HttpClient

 In the example used for custom services concept, add HttpModule to the [Link] to make use of
HttpClient class.

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


import { BrowserModule } from '@angular/platform-browser';
import {HttpClientModule} from '@angular/common/http'; import
{ AppComponent } from './[Link]';
import { BookComponent } from './book/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule], declarations:
[AppComponent, BookComponent], providers: [],
bootstrap: [AppComponent]
}
addBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' }); return
[Link]('[Link] book, { headers: options

catchError([Link]))
options }).pipe(
})
export class AppModule { }
Add the following code in [Link] file
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from
'@angular/common/http';
import { Observable, throwError } from 'rxjs'; import
{ catchError, tap } from 'rxjs/operators'; import
{ Book } from './book';
@Injectable({ providedIn:'root'
})
export class BookService {
booksUrl = '[Link]
constructor(private http: HttpClient) { } getBooks():
Observable<Book[]> {
return [Link]<Book[]>('[Link] tap((data:
any) => [Link]('Data Fetched:' + [Link](data))),
catchError([Link]));

}).pipe(
}
updateBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' }); return
49
YJRDMS COLLEGE OF ENGINEERING

[Link]<any>('[Link] book, { headers:

tap((_: any) => [Link](`updated hero id=${[Link]}`)), catchError([Link])


);
}
deleteBook(bookId: number): Observable<any>
{ const url = `${[Link]}/${bookId}`; return
[Link](url).pipe( catchError([Link]
r));
}
private handleError(err: HttpErrorResponse): Observable<any> { let
errMsg = '';
if ([Link] instanceof Error) {
// A client-side or network error occurred. Handle it accordingly. [Link]('An
error occurred:', [Link]);
errMsg = [Link];
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
[Link](`Backend returned code ${[Link]}`);
errMsg = [Link];}
return throwError(()=>errMsg);
}
}

 Write the code given below in [Link]


import { Component, OnInit } from '@angular/core';
import { BookService } from './[Link]';
import { Book } from './book'; @Component({
selector: 'app-book',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class BookComponent implements OnInit
{ title = 'Demo on HttpClientModule';
books!: Book[]; errorMessage!:
string; ADD_BOOK!: boolean;
UPDATE_BOOK!: boolean;
DELETE_BOOK!: boolean;
constructor(private bookService: BookService) { }
getBooks() { [Link]().subscribe({
next: books => [Link] = books, error:error
=> [Link] = <any>error
})
}
addBook(bookId: string, name: string): void { let
id=parseInt(bookId)
50
YJRDMS COLLEGE OF ENGINEERING

[Link]({id, name })
.subscribe({next:(book: any) => [Link](book)});
}
updateBook(bookId: string, name: string): void { let
id=parseInt(bookId)
[Link]({ id, name })
.subscribe({next:(book: any) => [Link] = book});
}
deleteBook(bookId: string): void { let
id=parseInt(bookId)
[Link](id)
.subscribe({next:(book: any) => [Link] = book});
}
ngOnInit() { [Link]();
}
}

Output:

51
YJRDMS COLLEGE OF ENGINEERING

9.b 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.

[Link]

[
{
"productId": 1,
"productName": "Samsung Galaxy Note 7", "productCode":
"MOB-120",
"description": "64GB, Coral Blue",
"price": 800,

}
{}]
"imageUrl": "assets/imgs/samsung_note7_coralblue.jpg", "manufacturer":
"Samsung",
"ostype": "Android", "rating": 4

"productId": 2,
"productName": "Samsung Galaxy Note 7", "productCode": "MOB-124",
"description": "64GB, Gold", "price": 850,
"imageUrl": "assets/imgs/samsung_note7_gold.jpg", "manufacturer":
"Samsung",
"ostype": "Android", "rating": 4

[Link]
[
{
"productId": 1,
"productName": "Apple iPad Mini 2", "productCode":
"TAB-120", "description": "16GB, White", "price": 450,
"imageUrl": "assets/imgs/apple_ipad_mini.jpg", "manufacturer":
"Apple",
"ostype": "iOS", "rating": 4

"productId": 2,
"productName": "Apple iPad Air2", "productCode":
"TAB-124", "description": "64GB, Black", "price":
600,
"imageUrl": "assets/imgs/ipad_air.jpg", "manufacturer":
52
YJRDMS COLLEGE OF ENGINEERING

"Apple",

53
YJRDMS COLLEGE OF ENGINEERING

{}]

Explore the methods present in the [Link] file from the products folder. Observe the
code given below:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators'
import { Product } from './product';
@Injectable()
export class ProductService
{ selectedProducts: any = [];
products: any = [];
producttype="tablet";
username: string = '';
// Fetches selectedProducts data from the sessionStorage
constructor(private http: HttpClient) {
if ([Link]('selectedProducts')) {
[Link] = [Link]([Link]('selectedProducts') + '');
}
}
// Makes a get request to backend to fetch products data
getProducts(): Observable<Product[]> {
if ([Link] === 'tablet') {
return [Link]<Product[]>('./assets/products/[Link]').pipe(
tap((products) => [Link] = products),
catchError([Link]));
} else if ([Link] === 'mobile') {
return [Link]<Product[]>('./assets/products/[Link]').pipe(
tap((products) => [Link] = products),
catchError([Link]));
}
else
throw new Error();
}
// Fetches the selected product details getProduct(id:
number): Observable<Product> {
return [Link]().pipe(
map(products => [Link](product => [Link] === id)[0]));
}
// Error Handling code
private handleError(err: HttpErrorResponse) {
return throwError(() => [Link]() || 'Server error');
}
}

54
YJRDMS COLLEGE OF ENGINEERING

Now open [Link] to explore adding service class to the module


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common'; import
{ FormsModule } from '@angular/forms';
import { ProductsRoutingModule } from './[Link]';
import { ProductListComponent } from './product-list/[Link]'; import {
ProductDetailComponent } from './product-detail/[Link]'; import
{ CartComponent } from './cart/[Link]';
import { OrderByPipe } from './product-list/[Link]';
import { RatingComponent } from './[Link]'; import {
ProductService } from './[Link]';
import { AuthGuardService } from './[Link]';
@NgModule({
imports: [ CommonModule,
FormsModule,
ProductsRoutingModule
],
declarations:
[ProductListComponent,ProductDetailComponent,CartComponent,OrderByPipe,RatingCompon ent],
providers:[ProductService,AuthGuardService]
})
export class ProductsModule { }
Now open the [Link] file to explore injecting a product service class
import { AfterViewInit, Component, ElementRef, OnInit, Renderer2, ViewChild } from
'@angular/core';
import { ProductService } from '../[Link]';
import { Cart } from '../cart/Cart';
import { Product } from '../product';
import { LoginService } from 'src/app/login/[Link]';
@Component({
templateUrl: '[Link]', styleUrls:
['[Link]']
})
export class ProductListComponent implements OnInit, AfterViewInit
{ chkman: any = [];
chkmanos: any = []; rate:
number = 0; pageTitle =
'mCart'; imageWidth = 80;
imageHeight = 120;
imageMargin = 12;
showImage = false;
listFilter: string = '';

55
YJRDMS COLLEGE OF ENGINEERING

manufacturers = [{ 'id': 'Samsung', 'checked': false },


{ 'id': 'Microsoft', 'checked': false },
{ 'id': 'Apple', 'checked': false },
{ 'id': 'Micromax', 'checked': false }
];
os = [{ 'id': 'Android', 'checked': false },
{ 'id': 'Windows', 'checked': false },
{ 'id': 'iOS', 'checked': false }];
price_range = [{ 'id': '300-450', 'checked': false },
{ 'id': '450-600', 'checked': false },
{ 'id': '600-800', 'checked': false },
{ 'id': '800-1000', 'checked': false }]; errorMessage:
string = '';
products: any = [];
selectedItems: any = 0; cart!:
Cart;
total = 0;
orderId = 0;
selectedManufacturers: string[] = [];
selectedOStypes: string[] = [];
selectedPrice: string[] = [];
checkedManufacturers: any[] = [];
checkedOS: any[] = []; checkedPrice:
any[] = [];
sub: any; i =
0;
sortoption = ''; chkmanosprice:
any = [];
@ViewChild('loginEl')
loginVal!: ElementRef;
@ViewChild('welcomeEl')
welcomeVal!: ElementRef;
// Fetches the products data from service class
constructor(private productService: ProductService, private loginService: LoginService, private
renderer: Renderer2) {
}
ngAfterViewInit() {
[Link] = [Link];
[Link] = [Link];
[Link]([Link], 'innerText', 'Logout');
[Link]([Link], 'display', 'inline');
let welcomeText="Welcome "+[Link]+ " ";
[Link]([Link], 'innerText', welcomeText);
[Link]([Link], 'color', '#ff0080');
}

56
YJRDMS COLLEGE OF ENGINEERING

ngOnInit() { [Link]++;
[Link]()
.subscribe({ next:products
=> {
[Link] = products;
[Link] = [Link];
[Link] =[Link]
},
error:error => [Link] = error});
if ([Link] > 0) {
[Link] = Number([Link]('selectedItems'));
[Link] = Number([Link]('grandTotal'));
}
}
checkManufacturers(cManuf: any[], cProducts: any[], chkman: any[]) { if
([Link] > 0) {
for (let checkManuf of cManuf) { for
(let checkProd of cProducts) {
if ([Link]() === [Link]()) {
[Link](checkProd);
}
}
}
} else {
[Link] = cProducts;
}
}
checkOpsystem(cOS: any[], chkman: any[], chkmanos: any[]) { if
([Link] > 0) {
for (let checkOS of cOS) {
for (let chkmann of chkman) {
if ([Link]() === [Link]()) { [Link](chkmann);
}
}
}
} else {
[Link] = chkman;
}
}
checkPrices(checkedPrice: any[], chkmanosprice: any[], chkmanos: any[]) { if
([Link] > 0) {
for (let checkPrice of checkedPrice) { for
(let chkmanfos of chkmanos) {
if (checkPrice === '300-450') {

57
YJRDMS COLLEGE OF ENGINEERING

if ([Link] >= 300 && [Link] <= 450) { [Link](chkmanfos);


}
}
if (checkPrice === '450-600') {
if ([Link] > 450 && [Link] <= 600) { [Link](chkmanfos);
}
}
if (checkPrice === '600-800') {
if ([Link] > 600 && [Link] <= 800) { [Link](chkmanfos);
}
}
if (checkPrice === '800-1000') {
if ([Link] > 800 && [Link] <= 1000) { [Link](chkmanfos);
}
}
}
}
} else {
[Link] = chkmanos;

}
}
// filtering functionality
filter(name: any) {
let checkedProducts: any[];
[Link] = []; [Link]
= []; [Link] = [];
const index = 0;
checkedProducts = [Link];

[Link] = ([Link]) ? false : true;


[Link] = [Link](product =>
[Link]).map(product => [Link]);
[Link] = [Link](product => [Link]).map(product => [Link]); [Link]
= this.price_range.filter(product => [Link]).map(product =>
[Link]);

[Link]([Link], checkedProducts, [Link]);


[Link]([Link], [Link], [Link]);
[Link]([Link], [Link], [Link]);

58
YJRDMS COLLEGE OF ENGINEERING

[Link] = [Link];
}
// Invoked when user clicks on Add to Cart button
// Adds selected product details to service class variable
// called selectedProducts
addCart(id: number) {
[Link] = new Cart();
[Link] += 1;
// fetching selected product details
const product = [Link]((currProduct: any) => [Link]
=== id)[0];
[Link] += [Link]; [Link]('selectedItems',
[Link]);
const sp = [Link]((currProduct: any) =>
[Link] === id)[0];
if (sp) {
const index = [Link]((currProduct: any) =>
[Link] === id);
[Link][index].quantity += 1;
[Link][index].totalPrice += [Link];
} else {
[Link] = 'ORD_' + [Link];
[Link] = id;
[Link] = [Link]('username') + '';
[Link] = [Link]; [Link] =
[Link];
[Link] = 1;
[Link] = new Date().toString(); [Link] =
[Link] * [Link];
[Link]([Link]);
[Link]('selectedProducts',
[Link]([Link]));
[Link]++;
}
}
// Search box functionality
// Searches based on manufacturer name searchtext()
{
[Link] = [Link]; if
([Link] > 0) {
[Link] = [Link]((product: Product) =>
[Link]().indexOf([Link]) !== -1);
}
}
// Invoked when a tab (Tablets/Mobiles) is clicked

59
YJRDMS COLLEGE OF ENGINEERING

// Displays tablets or mobiles data accordingly


tabselect(producttype: string) {
[Link] = [{ 'id': 'Samsung', 'checked': false },
{ 'id': 'Microsoft', 'checked': false },
{ 'id': 'Apple', 'checked': false },
{ 'id': 'Micromax', 'checked': false }
];
[Link] = [{ 'id': 'Android', 'checked': false },
{ 'id': 'Windows', 'checked': false },
{ 'id': 'iOS', 'checked': false }];
this.price_range = [{ 'id': '300-450', 'checked': false },
{ 'id': '450-600', 'checked': false },
{ 'id': '600-800', 'checked': false },
{ 'id': '800-1000', 'checked': false }]; [Link] =
[]; [Link] = producttype;
[Link]().subscribe({
next: products => { [Link] =
products; [Link]='';
},
error: error => [Link] = error
});

}
// Invoked when user select an option in sort drop down
// changes the sortoption value accordingly
onChange(value: string) {
[Link] = value;
}
}

Output:

60
YJRDMS COLLEGE OF ENGINEERING

10. Course Name: Angular JS


a Module Name: Routing Basics, Router Links
Create multiple components and add routing to provide navigation between them.

1. Consider the example used for the HttpClient concept.


2. 2. Create another component with the name dashboard using the following command

D:\MyApp>ng generate component dashboard


3. Open [Link] and add the following code

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


{ Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; import
{ Book } from '../book/book'; @Component({
selector: 'app-dashboard',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class DashboardComponent implements OnInit { books=[Link]
constructor(
private router: Router,
private book1Service: BooksdataService) { }
ngOnInit(): void { [Link]()
}
}
4. Open [Link] and add the following code
<h3>Top Books</h3>
<div class="grid grid-pad">
<div *ngFor="let b of books" class="col-1-4">
<div class="module book">
<h4>{{ b. name}}</h4>
<span><a [routerLink]="['/detail', [Link]]">Details</a></span>
</div>
</div>
</div>
5. Open [Link] and add the following code
[class*="col-"] {
float: left;
}
*,
*:after,
*:before {
-webkit-box-sizing: border-box;

61
YJRDMS COLLEGE OF ENGINEERING

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

62
YJRDMS COLLEGE OF ENGINEERING

max-height: 75px;
}
}
@media (max-width: 1024px) {
.grid { margin:
0;
}
.module {
min-width: 60px;
}
}
6. Create another component called book-detail using the following command D:\
MyApp>ng generate component bookDetail
7. Open [Link] and add getTopBooks() method as shown below to fetch s
pecific book details

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


@Injectable({
providedIn: 'root'
})
export class BooksdataService {
topBooks=[
{"id":1,"name":"HTML 5"},
{"id":2,"name":"CSS 3"},
{"id":3,"name":"Java Script"},
{"id":4,"name":"Ajax Programming"},
]
books=[
{"id":1,"name":"HTML 5"},
{"id":2,"name":"CSS 3"},
{"id":3,"name":"Java Script"},
{"id":4,"name":"Ajax Programming"},
{"id":5,"name":"jQuery"},
{"id":6,"name":"Mastering [Link]"},
{"id":7,"name":"Angular JS 1.x"},
{"id":8,"name":"ng-book 2"},
{"id":9,"name":"Backbone JS"},
{"id":10,"name":"Yeoman"}
]
constructor() { }
getTopBooks(){
return [Link]([Link])
}
}

63
YJRDMS COLLEGE OF ENGINEERING

8. Open [Link] and add the following code


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Book } from '../book/book';
import { BooksdataService } from '../book/[Link]';
@Component({
selector: 'app-book-detail',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class BookDetailComponent implements OnInit {
constructor(private route:ActivatedRoute, private bdetails:BooksdataService) { }
bookid:any;
book:any; ngOnInit():
void {

[Link]( param
s=>{
let n = [Link]("id");
[Link]=Number(n);
[Link]=[Link](m=>[Link]==[Link])
}
)
}
goBack() {
[Link]();
}
}

9. Open [Link] and add the following code


<div *ngIf="book">
<h2>{{ [Link] }} details!</h2>
<div><label>id: </label>{{ [Link] }}</div>
<div>
<label>name: </label> <input [(ngModel)]="[Link]" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
10. Open [Link] and add the following code
label {
display: inline-block;
width: 3em;
margin: 0.5em 0;
color: #607d8b; font-
weight: bold;
}

64
YJRDMS COLLEGE OF ENGINEERING

input { height:
2em;
font-size: 1em; padding-
left: 0.4em;
}
button {
margin-top: 20px;
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer; cursor:
hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled
{ background-color: #eee;
color: #ccc;
cursor: auto;
}
11. Generate PageNotFound component using the following CLI command D:\
MyApp>ng g c PageNotFound
12. Add below code to [Link]:
<div>
<h1>404 Error</h1>
<h1>Page Not Found</h1>
</div>
13. Add the below code to [Link]:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ BookDetailComponent } from './book-detail/[Link]';
import { PageNotFoundComponent } from './page-not-found/[Link]'; const
appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'books', component: BookComponent },
{ path: 'detail/:id', component: BookDetailComponent },
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({ imports: [

65
YJRDMS COLLEGE OF ENGINEERING

[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }

14. Write the below-given code in [Link]


15. import { BooksdataService } from './book/[Link]';
16. import { NgModule } from '@angular/core';
17. import { BrowserModule } from '@angular/platform-browser';
18. import { HttpClientModule } from '@angular/common/http';
19. import { FormsModule } from '@angular/forms';
20. import { AppComponent } from './[Link]';
21. import { BookComponent } from './book/[Link]';
22. import { DashboardComponent } from './dashboard/[Link]';
23. import { BookDetailComponent } from './book-detail/[Link]';
24. import { AppRoutingModule } from './[Link]';
25. import { PageNotFoundComponent } from './page-not-found/[Link]';
26. @NgModule({
27. imports: [BrowserModule, HttpClientModule, FormsModule, AppRoutingModule],
28. declarations: [AppComponent, BookComponent, DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
29. providers: [BooksdataService],
30. bootstrap: [AppComponent]
31. })
32. export class AppModule { }
15. Write the below-given code in [Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./[Link]'],
templateUrl: './[Link]'
})
export class AppComponent { title
= 'Tour of Books';
}
16. Write the below-given code in [Link]
<h1>{{title}}</h1>
<nav>
<a [routerLink]='["/dashboard"]' routerLinkActive="active">Dashboard</a>
<a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
</nav>
<router-outlet></router-outlet>
17. Open [Link] and add the following code

66
YJRDMS COLLEGE OF ENGINEERING

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

67
YJRDMS COLLEGE OF ENGINEERING

background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link
{ color: #607D8B;
}
nav a:hover { color:
#039be5;
background-color: #CFD8DC;
}
nav [Link] { color:
#039be5;
}
/* everywhere else */
*{
font-family: Arial, Helvetica, sans-serif;
}
18. Open [Link] under the src folder and add the following code
/* You can add global styles to this file, and also import other style files */ body{
padding:10px;
}
19. Open [Link] file in book folder and add the following code
import { Component, OnInit } from '@angular/core';
import { BooksdataService } from './[Link]';
@Component({
selector: 'app-book',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class BookComponent implements OnInit {

constructor(private displayBooks: BooksdataService) { } books=[Link];


ngOnInit(): void {
[Link];
}
}

21. Open [Link] and update with below code.


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

68
YJRDMS COLLEGE OF ENGINEERING

Output:

69
YJRDMS COLLEGE OF ENGINEERING

10. Course Name: Angular JS


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 in another tab or window, or if the user tries

Create a LoginComponent using Angular CLI ng g


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

70
YJRDMS COLLEGE OF ENGINEERING

username: [],
password: [],
});
}
onFormSubmit(): void {
const uname = [Link]; const
pwd = [Link];
[Link]
.isUserAuthenticated(uname, pwd)
.subscribe({next:(authenticated) => { if
(authenticated) {
[Link](['/books']);
} else {
[Link] = 'Invalid Credentials. Try again.';
}
}});
}
}
Add the following code to the [Link] file inside Login folder export
class User {
constructor(public userId: number, public username: string, public password: string) { }
}

Add the following code to the [Link] file present inside login folder.
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from './user';
const USERS = [
new User(1, 'user1', 'user1'),
new User(2, 'user2', 'user2')
];
const usersObservable = of(USERS);
@Injectable({
providedIn: 'root'
})
export class LoginService { private
isloggedIn = false;
getAllUsers(): Observable<User[]> { return
usersObservable;
}
isUserAuthenticated(username: string, password: string): Observable<boolean> { return
[Link]().pipe(
map(users => {
const Authenticateduser = [Link](user => ([Link] === username) &&
([Link] === password));

71
YJRDMS COLLEGE OF ENGINEERING

if (Authenticateduser)
{ [Link] = true;
} else {
[Link] = false;
}
return [Link];
})
);
}
isUserLoggedIn(): boolean
{ return [Link];
}
}
Create another service class called [Link] inside login folder and add the
following code:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router'; import
{ LoginService } from './[Link]'; @Injectable({
providedIn: 'root'
})
export class LoginGuardService implements CanActivate { constructor(private
loginService: LoginService, private router: Router) { } canActivate(): boolean {
if ([Link]()) { return
true;
}
[Link](['/login']);
return false;
}
}
Add the following code in [Link]
...
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{path: 'login',component:LoginComponent},
{ path: 'books', component: BookComponent, canActivate:[LoginGuardService] },
{ path: 'dashboard', component: DashboardComponent},
{ path: 'detail/:id', component: BookDetailComponent},
{ path: '**', component: PageNotFoundComponent },
];
...

72
YJRDMS COLLEGE OF ENGINEERING

Update [Link] as below:


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

Output:

73
YJRDMS COLLEGE OF ENGINEERING

10. Course Name: Angular JS


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 tab and check the Load time

1. Create a book-routing module using below command ng


g module book –routing

2. Write the code given below in the [Link] file inside book folder.
import { authGuard } from './../login/[Link]';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './[Link]'; const
bookRoutes: Routes = [
{
path: '',
component: BookComponent,
canActivate: [authGuard]
}
];
@NgModule({
imports: [[Link](bookRoutes)],
exports: [RouterModule]
})
export class BookRoutingModule { }
3. Create the [Link] file inside book folder and add the following code
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BookComponent } from './[Link]';
import { BookRoutingModule } from './[Link]';
@NgModule({
imports: [CommonModule, BookRoutingModule], declarations:
[BookComponent]
})
export class BookModule { }
4. Add the following code to the [Link] file
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookDetailComponent } from './book-detail/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ LoginComponent } from './login/[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not-
[Link]';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },

74
YJRDMS COLLEGE OF ENGINEERING

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


{ path: 'books', loadChildren: () => import('./book/[Link]').then(m =>
[Link]) },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent} ,
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({ imports
:[
[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
5. Add the following code to the [Link] file
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'; import
{ HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './[Link]';
import { BookComponent } from './book/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ BookDetailComponent } from './book-detail/[Link]'; import
{ AppRoutingModule } from './[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not-
[Link]';
import { LoginComponent } from './login/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule,
ReactiveFormsModule,FormsModule, AppRoutingModule],
declarations: [AppComponent, LoginComponent, DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

75
YJRDMS COLLEGE OF ENGINEERING

Output:

76
YJRDMS COLLEGE OF ENGINEERING

77
YJRDMS COLLEGE OF ENGINEERING

10. Course Name: Angular JS


d Module Name: Nested Routes
Implement Child Routes to a submodule.

1. Add below code to routing module [Link] to implement child


routing in the book module.
2. import { NgModule } from '@angular/core';
3. import { RouterModule, Routes } from '@angular/router';
4. import { BookComponent } from './[Link]';
5. import { authGuard} from '../login/[Link]';
6. import { DashboardComponent } from '../dashboard/[Link]';
7. import { BookDetailComponent } from '../book-detail/[Link]';
8. const bookRoutes: Routes = [
9. {
10. path: '',
11. component: BookComponent,
12. children: [
13. { path: 'dashboard', component: DashboardComponent },
14. { path: 'detail/:id', component: BookDetailComponent }
15. ],
16. canActivate: [authGuard]
17. }];
18. @NgModule({
19. imports: [[Link](bookRoutes)],
20. exports: [RouterModule]
21. })
22. export class BookRoutingModule { }
[Link] BookRoutingModule in the submodule [Link] as shown below:

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


BookComponent } from './[Link]';
import { BookRoutingModule } from './[Link]'; import
{ FormsModule } from '@angular/forms';
import { BookDetailComponent } from '../book-detail/[Link]'; import
{ DashboardComponent } from '../dashboard/[Link]'; import
{ CommonModule } from '@angular/common';
@NgModule({
imports: [ CommonModule, BookRoutingModule, FormsModule],
declarations: [BookComponent, BookDetailComponent, DashboardComponent]
})
export class BookModule { }

78
YJRDMS COLLEGE OF ENGINEERING

3. Write the following code in [Link].

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


import { RouterModule, Routes } from '@angular/router'; import {
LoginComponent } from './login/[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not-
[Link]';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'books', loadChildren: () => import('./book/[Link]').then(m => [Link]) },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({ import
s: [
[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }

5. Write the following code in [Link]


<h1>{{title}}</h1>
<nav>
<a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
</nav>
<router-outlet></router-outlet>
5. Write the below code in [Link]
import { NgModule } from '@angular/core';
import { BookComponent } from './[Link]';
import { BookRoutingModule } from './[Link]'; import
{ FormsModule } from '@angular/forms';
import { BookDetailComponent } from '../book-detail/[Link]'; import
{ DashboardComponent } from '../dashboard/[Link]'; import
{ CommonModule } from '@angular/common';
@NgModule({
imports: [ CommonModule, BookRoutingModule, FormsModule],
declarations: [BookComponent, BookDetailComponent, DashboardComponent]
})
export class BookModule { }

79
YJRDMS COLLEGE OF ENGINEERING

6. Write the following code in [Link].


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './[Link]'; import
{ authGuard} from '../login/[Link]';
import { DashboardComponent } from '../dashboard/[Link]'; import {
BookDetailComponent } from '../book-detail/[Link]'; const
bookRoutes: Routes = [
{
path: '',
component: BookComponent,
children: [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent }
],
canActivate: [authGuard]
}];
@NgModule({
imports: [[Link](bookRoutes)],
exports: [RouterModule]
})
export class BookRoutingModule { }
7. Write the below code in [Link]
<br/>
<h2>MyBooks</h2>
<ul class="books">
<li *ngFor="let book of books " (click)="gotoDetail(book)">
<span class="badge">{{[Link]}}</span> {{[Link]}}
</li>
</ul>
<div>
<router-outlet></router-outlet>
</div>
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
8. Write the below code in [Link]:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Book } from './book';
import { BookService } from './[Link]';
@Component({
selector: 'app-book',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class BookComponent implements OnInit
{ books: Book[]=[];

80
YJRDMS COLLEGE OF ENGINEERING

errorMessage!: string;
constructor(private bookService: BookService, private router: Router) { }
getBooks() {
[Link]().subscribe({
next: books => {[Link](books);[Link] = books},
error:error => [Link] = <any>error
})
}
gotoDetail(book: Book): void
{ [Link](['/books/detail/', [Link]]);
}
ngOnInit(): void {
[Link]();
}
}
9. Update [Link] as below:
<div *ngIf="book">
<h2>{{ [Link] }} details!</h2>
<div><label>id: </label>{{ [Link] }}</div>
<div>
<label>name: </label> <input [(ngModel)]="[Link]" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
[Link] [Link] as below:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Book } from '../book/book';
import { BooksdataService } from '../book/[Link]';
@Component({
selector: 'app-book-detail',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class BookDetailComponent implements OnInit {
constructor(private route:ActivatedRoute, private bdetails:BooksdataService, private r:Router)
{}
bookid:any; book:any;
ngOnInit(): void {

[Link]( params=
>{
let n = [Link]("id"); [Link]=Number(n);
[Link]=[Link](m=>[Link]==[Link])

81
YJRDMS COLLEGE OF ENGINEERING

}
)
}
goBack() {
[Link](['/books'])
}
}

Output:

82
YJRDMS COLLEGE OF ENGINEERING

MONGODB
11. Course Name: MongoDB Essentials - A Complete MongoDB Guide
a Module Name: Installing MongoDB on the local computer, Create MongoDB Atlas
Cluster
Install MongoDB and configure ATLAS

Steps to Install MongoDB Atlas


Follow the below steps to install MongoDB Atlas.
Step 1: Go to the MongoDB website and sign up. Enter your credentials and click on Create
Account and then verify the account or just click Sign Up with GoogleID and select the ID from
which you want to register.

Step 2: Now select the Shared option and click on Create for free usage.

83
YJRDMS COLLEGE OF ENGINEERING

Step 3: Now select cloud provider AWS or Google cloud for free hosting and then select the region
in which it should be hosted. And in the Cluster tier select M0 Sandbox for the free environment.
And If you want you can rename the cluster. It will take 4-5 minutes to set up the environment.

Step 4: Create a username and password then select database access to atlasAdmin and network
access to allow access to anywhere. That will be the username and password through which the user
can access the database given to who do you give access.

84
YJRDMS COLLEGE OF ENGINEERING

Step 5: Select Connect and then select connect with the MongoDB Shell then go to I have
MongoDB shell installed. Select the node version from there. And after that run the command in the
command line which is given. Then enter the password which the user has set earlier with the
username and password.

Step 6: Go to Connect then Connect your application select your node version. Now copy the
link given and paste it into your application where you connect MongoDB. And replace
<password> with your password.

And that’s it. Now you are connected with the MongoDB atlas.

85
YJRDMS COLLEGE OF ENGINEERING

11. Course Name: MongoDB Essentials - A Complete MongoDB Guide


b Module Name: Introduction to the CRUD Operations
Write MongoDB queries to perform CRUD operations on document using insert(),
find(), update(), remove()

How to perform CRUD operations

Now that we've defined MongoDB CRUD operations, we can take a look at how to carry out the
individual operations and manipulate documents in a MongoDB database. Let's go into the processes
of creating, reading, updating, and deleting documents, looking at each operation in turn.

Create operation

For MongoDB CRUD, if the specified collection doesn't exist, the create operation will create the
collection when it's executed. Create operations in MongoDB target a single collection, not multiple
collections. Insert operations in MongoDB are atomic on a single document level.
MongoDB provides two different create operations that you can use to insert documents into a
collection:
 [Link]()
 [Link]()

86
YJRDMS COLLEGE OF ENGINEERING

insertOne()

[Link]({ name:
"Marsh",
age: "6 years", species:
"Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true
})

insertMany()
[Link]([{ name:
"Marsh",
age: "6 years",
species: "Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true},
{name: "Kitana",
age: "4 years",
species: "Cat",
ownerAddress: "521 E. Cortland", chipped:
true}])
Read operations
The read operations allow you to supply special query filters and criteria that let you specify which
documents you want. The MongoDB documentation contains more information on the available
query filters. Query modifiers may also be used to change how many results are returned.
MongoDB has two methods of reading documents from a collection:
 [Link]()
 [Link]()

find()
[Link]()
[Link]({"species":"Cat"})

87
YJRDMS COLLEGE OF ENGINEERING

Update operations
Like create operations, update operations operate on a single collection, and they are atomic at a single
document level. An update operation takes filters and criteria to select the documents you want to
update.

You should be careful when updating documents, as updates are permanent and can’t be rolled back.
This applies to delete operations as well.

For MongoDB CRUD, there are three different methods of updating documents:

 [Link]()
 [Link]()
 [Link]()

updateOne()

[Link]({name: "Marsh"}, {$set:{ownerAddress: "451 W. Coffee


St. A204"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "6
years", "species}

Delete operations
Delete operations operate on a single collection, like update and create operations. Delete operations are
also atomic for a single document. You can provide delete operations with filters and criteria to
specify which documents you would like to delete from a collection. The filter options rely on the
same syntax that read operations utilize.
MongoDB has two different methods of deleting records from a collection:
 [Link]()
 [Link]()
deleteOne() [Link]({name:"Maki"})
{ "acknowledged" : true, "deletedCount" : 1 }
> [Link]()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4
years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5",
"species" : "Dog", "ownerAddress" : "451 W. Coffee St. A204", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5",
"species" : "Dog}

88
YJRDMS COLLEGE OF ENGINEERING

12. Course Name: MongoDB Essentials - A Complete MongoDB Guide


a Module Name: Create and Delete Databases and Collections
Write MongoDB queries to Create and drop databases and collections.

Creating a Database and Collection in MongoDB Step


1: Create a Database In MongoDB
To create a database in MongoDB use the “use” command.
Syntax
use database_name
Example
We have created a MongoDB database named gfgDB, as shown in the image below:

Here, we have created a database named as “gfgDB”. If the database doesn’t exist,
MongoDB will create the database when you store any data to it.
View all the Existing Databases
To view all existing databases in MongoDB use the “show dbs” command.
Syntax
show dbs

This command returns a list of all the existing MongoDB databases.

89
YJRDMS COLLEGE OF ENGINEERING

Step 2: Create a Collection in MongoDB


To create a collection in MongoDB use the createCollection() method. Collection
name is passed as argument to the method.
Syntax
[Link](‘ collection_name’ );
Example
Creating collection named “Student” in MongoDB
[Link]('Student');

Output:

90
YJRDMS COLLEGE OF ENGINEERING

12. Course Name: MongoDB Essentials - A Complete MongoDB Guide


b Module Name: Introduction to MongoDB Queries
Write MongoDB queries to work with records using find(), limit(), sort(),
createIndex(), aggregate().

MongoDB – limit() Method


Syntax:
[Link]()
Or [Link](<query>).limit(<number>)
Examples of MonoDB limit()
In the following examples, we are working with:
Database: geeksforgeeks
Collections: gfg
Document: Eight documents contains the content
Output:

[Link]()
[Link](query, projection, options)

[Link]()
[Link](keys, options, commitQuorum)

91

You might also like