MSD Lab
MSD Lab
4a Property Binding 23
5a Built in Pipes 26
1
EX_NO DATE EXPERIMENTS PG_NO MARKS SIGNATURE
2
EXERCISE-1
1a)Aim: 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.
Source Code:
Logincomponent.css:
.container-styles{
position: relative;
top: 180px;
width:50%
}
.padding{
padding-bottom:0px;
margin-bottom:0px;
}
.link-underline{
color:#337ab7;
text-decoration: underline;
}
.error{
color: red;
position:relative;
left:50px;
}
.valid {
border-left: 5px solid #42A948; /* green */
}
.invalid{
border-left: 5px solid #a94442; /* red */}
Logincomponent.html:
<!-- Login form-->
<div class="container container-styles">
<div class="col-xs-7 col-xs-offset-3">
<div class="panel panel-primary">
3
<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="formcontrol"[ngClass]="{'valid':loginForm.controls['userName'].valid,
'invalid':loginForm.controls['userName'].invalid&&!loginForm.controls['userName'].pristine}"
formControlName="userName">
<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':loginForm.controls['password'].valid,
'invalid':loginForm.controls['password'].invalid && !loginForm.controls['password'].pristine}"
formControlName="password">
</div>
<div *ngIf="!valid" class="error">Invalid Credentials...Please try again...</div>
<br />
<div class="form-group">
<span class="col-xs-4"></span>
<div class="col-xs-3">
<button (click)="onSubmit()" class="btn btn-primary" [disabled]="!loginForm.valid">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>
</div>
</div></div>
</div>
login.component:
import { Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
4
import { Login } from './Login';
import { LoginService } from './login.service';
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
login = new Login();
users: Login[] = [];
valid = true;
ngOnInit() {
// Makes a service call to fetch users data from the backend
this.loginService.getUsers().subscribe({next:users => this.users = users});
this.loginForm = this.formBuilder.group({
userName: [this.login.userName, Validators.required],
password: [this.login.password, Validators.required]
})
}
onSubmit() {
//fetches the form object containing the values of all the form controls
this.login = this.loginForm.getRawValue();
const user = this.users.filter(currUser => currUser.userName === this.login.userName && currUser.password ===
this.login.password)[0];
if (user) {
this.loginService.username = this.login.userName;
this.router.navigate(['/products']);
} else {
this.valid = false;
}
}
}
Loginservice.ts:
import { ElementRef, Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
5
import { catchError } from 'rxjs/operators';
import { Login } from './Login';
@Injectable({
providedIn: 'root'
})
export class LoginService {
username = '';
loginElement!: ElementRef;
welcomeElement!: ElementRef;
constructor(private http: HttpClient) {}
// Makes a get request to the backend to fetch users data
getUsers(): Observable<Login[]> {
return this.http.get<Login[]>('./assets/users/users.json').pipe(
catchError(this.handleError));
}
// Invoked if an error is thrown in the get request
private handleError(err: HttpErrorResponse) {
console.error(err);
return throwError(()=>err.error() || 'Server error');
}
}
Login.ts:
//model for Login
export class Login {
public userName: string='';
public password: string='';
}
Product.ts:
// Product model
export class Product {
constructor(public productId: number,
public productName: string,
public productCode: string,
public price: number,
public description: string,
6
public rating:number,
public imageUrl: string, public manufacturer: string) {
}
}
Product.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
FormsModule,
ProductsRoutingModule
],
declarations: [ProductListComponent, ProductDetailComponent, CartComponent, OrderByPipe, RatingComponent],
providers: [ProductService, AuthGuardService]
})
export class ProductsModule { }
rating.component.ts
// Rating Component which displays the number of stars based on the input given
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-rating',
template: `
<span *ngFor="let r of range; let i = index">
<i class="glyphicon" [ngClass]="i < rate ? 'glyphicon-star' : 'glyphicon-star-empty'"></i>
</span>
`
})
export class RatingComponent {
range: Array<number> = [1, 2, 3, 4, 5];
@Input() rate: number=0;
}
Output :
7
1b. Aim:Create a new component called hello and render Hello Angular on the page
Source Code:
hello.component.ts :
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
courseName: string = "Angular";
constructor() { }
ngOnInit() {
}
}
hello.component.css:
p{
color:blue;
font-size:20px;
}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello/hello.component';
@NgModule({
imports: [BrowserModule,AppRoutingModule],
declarations: [AppComponent, HelloComponent],
8
providers: [],
bootstrap: [HelloComponent]
})
export class AppModule { }
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
</head>
<body>
<app-hello></app-hello>
</body>
</html>
Output:
1c.Aim:Add an event to the hello component template and when it is clicked, it should change the courseName.
Source Code:
hello.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: "./hello.component.html",
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
courseName = "Angular";
constructor() { }
ngOnInit() {
}
changeName() {
9
this.courseName = "TypeScript";
}
}
hello.component.html:
<h1>Welcome</h1>
<h2>Course Name: {{ courseName }}</h2>
<p (click)="changeName()">Click here to change</p>
Output:
}
}
Welcome.component.html
<!-- Welcome page -->
<div class="container container-styles">
<div class="panel panel-primary">
<div class="panel-heading">{{pageTitle}}</div>
10
<div class="panel-body">
<div class="row">
<span class="img-responsive center-block logo-styles">
<span class="glyphicon glyphicon-shopping-cart"> </span>
</span>
<div id="div1" class="shadow title-styles">mCart</div>
</div><br />
<div class="row">
<div class="text-center text-styles">An online app to purchase mobile gadgets</div>
</div>
</div>
</div>
</div>
Login.ts
export class Login {
public userName: string='';
public password: string='';
}
Login.component.ts
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 './login.service';
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [LoginService]
})
export class LoginComponent implements OnInit {
login = new Login();
...
onSubmit() {
11
//logic for validation
}
}
App.module.ts
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { WelcomeComponent } from './welcome/welcome.component';
import { LoginComponent } from './login/login.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule, AppRoutingModule],
declarations: [AppComponent, WelcomeComponent, LoginComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
output
12
EXERCISE-2
2a.Aim: 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.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
isAuthenticated!: boolean;
submitted = false;
userName!: string;
onSubmit(name: string, password: string) {
this.submitted = true;
this.userName = name;
if (name === 'admin' && password === 'admin') {
this.isAuthenticated = true;
} else {
this.isAuthenticated = false;
}
}
}
app.component.html:
<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>
13
<button (click)="onSubmit(username.value, password.value)">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>
app.module.ts :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
index.html :
<!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="favicon.ico">
14
</head>
<body>
<app-root></app-root>
</body>
</html>
Output:
2b.Aim: Create a courses array and rendering it in the template using ngFor directive in a list format.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
courses: any[] = [
{ id: 1, name: 'TypeScript' },
{ id: 2, name: 'Angular' },
{ id: 3, name: 'Node JS' },
{ id: 1, name: 'TypeScript' }
];
}
15
app.component.html:
<ul>
<li *ngFor="let course of courses; let i = index">
{{ i }} - {{ course.name }}
</li>
</ul>
Output:
2c.Aim:Display the correct option based on the value passed to ngSwitch directive.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
choice = 0;
nextChoice() {
this.choice++;
}
}
app.component.html:
<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>
16
<p *ngSwitchCase="2">Second Choice Again</p>
<p *ngSwitchDefault>Default Choice</p>
</div>
<div>
<button (click)="nextChoice()">
Next Choice
</button>
</div>
Output:
2d.Aim:Create a custom structural directive called 'repeat' which should repeat the element given a number of times.
Source Code:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { RepeatDirective } from './repeat.directive';
@NgModule({
declarations: [
AppComponent,
RepeatDirective ],
imports: [
BrowserModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
17
repeat.directive.ts:
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++) {
this.viewContainer.createEmbeddedView(this.templateRef);
}}
}
app.component.html:
<h3>Structural Directive</h3>
<p *appRepeat="5">I am being repeated...</p>
Output:
18
EXERCISE-3
3a.Aim: Apply multiple CSS properties to a paragraph in a component using ngStyle.
Source Code:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
colorName = 'red';
fontWeight = 'bold';
borderStyle = '1px solid black';
}
app.component.html
<p [ngStyle]="{
color:colorName,
'font-weight':fontWeight,
borderBottom: borderStyle
}">
Demo for attribute directive ngStyle
</p>
Output:
19
3b.Aim:Apply multiple CSS classes to the text using ngClass directive.
Source Code:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isBordered = true;
}
app.component.html:
<div [ngClass]="{bordered: isBordered}">
Border {{ isBordered ? "ON" : "OFF" }}
</div>
app.component.css:
.bordered {
border: 1px dashed black;
background-color: #eee;
}
Output:
20
3c.Aim: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.
Source Code:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MessageDirective } from './message.directive';
@NgModule({
declarations: [
AppComponent,
MessageDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
message.directive.ts:
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) {
renderer.setStyle(el.nativeElement, 'cursor', 'pointer');
}
}
app.component.html:
<h3>Attribute Directive</h3>
<p [appMessage]="myMessage">Click Here</p>
21
app.component.css:
h3 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
p{
color: #ff0080;
font-family: Arial, Helvetica, sans-serif;}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myMessage = 'Hello, I am from attribute directive';
}
Output:
22
EXERCISE-4
4a. Aim:Binding image with class property using property binding.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
imgUrl = 'assets/imgs/logo.png';
}
app.component.html:
<img [src]='imgUrl'>
Output:
23
styleUrls: ['./app.component.css']
})
export class AppComponent {
colspanValue = '2';
}
app.component.html:
<table border=1>
<tr>
<td [attr.colspan]="colspanValue"> First </td>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
<td>Fourth</td>
<td>Fifth</td>
</tr>
</table>
Output:
4c.Aim:Binding an element using inline style and user actions like entering text in input fields.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
24
}
app.component.html:
<input type="text" [(ngModel)]="name"> <br/>
<div>Hello , {{ name }}</div>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
25
EXERCISE-5
5a.Aim:Display the product code in lowercase and product name in uppercase using built-in pipes.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'product details';
productCode = 'PROD_P001';
productName = 'Laptop';
}
app.component.html:
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<td> {{ productCode | lowercase }} </td>
</tr>
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
</table>
Output:
26
5b.Aim:Apply built-in pipes with parameters to display product details.
Source Code:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
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;
}
app.component.html:
<h3> {{ title | titlecase}} </h3>
<table style="text-align:left">
<tr>
<th> Product Code </th>
<td> {{ productCode | slice:5:9 }} </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>
27
<td>{{ productRating | number:'1.3-5'}} </td>
</tr>
</table>
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { registerLocaleData } from '@angular/common';
import localeFrench from '@angular/common/locales/fr';
registerLocaleData(localeFrench);
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
28
5c.Aim:Load CourseslistComponent in the root component when a user clicks on the View courses list button.
Source Code:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CoursesListComponent } from './courses-list/courses-list.component';
@NgModule({
declarations: [
AppComponent,
CoursesListComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
courses-list.component.ts
import { Component, OnInit } from '@angular/core';
export class CoursesListComponent {
courses = [
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
}
courses-list.component.html:
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
29
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ course.courseId }}</td>
<td>{{ course.courseName }}</td>
</tr>
</tbody>
</table>
app.component.html:
<h2>Popular Courses</h2>
<button (click)="show = true">View Courses list</button><br /><br />
<div *ngIf="show">
<app-courses-list></app-courses-list>
</div>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
show!: boolean;
}
Output:
30
EXERCISE-6
6a.Aim: Create an AppComponent that displays a dropdown with a list of courses as values in it. Create another
component called CoursesList component and load it in AppComponent which should display the course details. When a
user selects a course from the dropdown, corresponding course details should be loaded.
Source Code:
courses-list.component.ts:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './courses-list.component.html',
styleUrls: ['./courses-list.component.css'],
})
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) {
this.course = [];
for (var i = 0; i < this.courses.length; i++) {
if (this.courses[i].courseName === name) {
this.course.push(this.courses[i]);
}}
}}
Courses-list.component.html :
<table border="1" *ngIf="course.length > 0">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
31
</thead>
<tbody>
<tr *ngFor="let c of course">
<td>{{ c.courseId }}</td>
<td>{{ c.courseName }}</td>
</tr>
</tbody>
</table>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
name!: string;
}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CoursesListComponent } from './courses-list/courses-list.component';
@NgModule({
declarations: [
AppComponent,
CoursesListComponent ],
imports: [
BrowserModule,
AppRoutingModule ],
providers: [],
bootstrap: [AppComponent]
})
32
export class AppModule { }
Output:
6b.Aim:Create an AppComponent that loads another component called 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 the register button, it should send that courseName value back to AppComponent where
it should display the registration successful message along with courseName.
Source code:
courses-list.component.ts:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './courses-list.component.html',
styleUrls: ['./courses-list.component.css']
})
export class CoursesListComponent {
@Output() registerEvent = new EventEmitter<string>();
courses = [
{ courseId: 1, courseName: 'Node JS' },
{ courseId: 2, courseName: 'Typescript' },
{ courseId: 3, courseName: 'Angular' },
{ courseId: 4, courseName: 'React JS' }
];
register(courseName: string) {
this.registerEvent.emit(courseName);
}
}
33
Courses-list.component.html:
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ course.courseName }}</td>
<td><button (click)="register(course.courseName)">Register</button></td>
</tr>
</tbody>
</table>
app.component.html:
<h2>Courses List</h2>
<app-courses-list (registerEvent)="courseReg($event)"></app-courses-list>
<div *ngIf="message">{{ message }}</div>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message!: string;
courseReg(courseName: string) {
this.message = `Your registration for ${courseName} is successful`;
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
34
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [
AppComponent,
CoursesListComponent
],
imports: [
BrowserModule,
AppRoutingModule],
export class AppModule { }
Output:
35
<div class="cmp">Second Component</div>
second.component.ts:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class SecondComponent {
}
app.component.css:
.cmp {
padding: 8px;
margin: 6px;
border: 2px solid red;
}
app.component.html:
<h3>CSS Encapsulation with Angular</h3>
<div class="cmp">
App Component
<app-first></app-first>
<app-second></app-second>
</div>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = '6c';}
second.component.ts:
import { Component, ViewEncapsulation } from '@angular/core';
36
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css'],
encapsulation: ViewEncapsulation.None
})
export class SecondComponent {
}
Output:
6d.Aim: Override component life-cycle hooks and logging the corresponding messages to understand the flow.
Source Code:
Child.component.html:
<h2>Child Component</h2>
<h2>{{title}}</h2>
Child.component.ts:
import { Component, OnChanges, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() title!: string;
ngOnChanges(changes: any): void {
console.log('changes in child:' + JSON.stringify(changes));
}
}
app.component.html:
<div>
37
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]="data" />
<app-child [title]="data"></app-child>
</div>
app.component.ts:
import {
Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, DoCheck,
AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy {
data = 'Angular';
ngOnInit() {
console.log('Init');
}
ngDoCheck(): void {
console.log('Change detected');
}
ngAfterContentInit(): void {
console.log('After content init');
}
ngAfterContentChecked(): void {
console.log('After content checked');
}
ngAfterViewInit(): void {
console.log('After view init');
}
38
ngAfterViewChecked(): void {
console.log('After view checked');
}
ngOnDestroy(): void {
console.log('Destroy');
}
}
Output:
EXERCISE-7
7b.Aim: Create an employee registration form as a reactive form.
Source Code:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { RegistrationFormComponent } from './registration-form/registration-form.component';
@NgModule({
declarations: [
AppComponent,
RegistrationFormComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
39
bootstrap: [AppComponent]
})
export class AppModule { }
registration-form.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.css']
})
export class RegistrationFormComponent implements OnInit {
registerForm!: FormGroup;
submitted!:boolean;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
address: this.formBuilder.group({
street: [],
zip: [],
city: []
})
});
}
}
registration-form.component.html:
<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="registerForm.controls['firstName'].errors" class="alert alert-danger">
40
Firstname field is invalid.
<p *ngIf="registerForm.controls['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>
<button type="submit" class="btn btn-primary" (click)="submitted=true">Submit</button>
</form>
<br/>
</div>
registration-form.component.css:
.ng-valid[required] {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
app.component.html:
<app-registration-form></app-registration-form>
Output:
7c.Aim: Create a custom validator for an email field in the employee registration form ( reactive form).
Source Code:
registration-form.component.html:
41
<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="registerForm.controls['firstName'].errors" class="alert alert-danger">
Firstname field is invalid.
<p *ngIf="registerForm.controls['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="registerForm.controls['lastName'].errors" class="alert alert-danger">
Lastname field is invalid.
<p *ngIf="registerForm.controls['lastName'].errors?.['required']">This field is required!</p>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" formControlName="email" />
<div *ngIf="registerForm.controls['email'].errors" class="alert alert-danger">
Email field is invalid.
<p *ngIf="registerForm.controls['email'].errors?.['required']">
This field is required!
</p>
<p *ngIf="registerForm.controls['email'].errors?.['emailInvalid']">
{{ registerForm.controls['email'].errors?.['emailInvalid'].message }}
</p>
</div>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted=true">Submit</button>
</form>
<br/>
42
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p> Zip: {{ registerForm.get('address.zip')?.value }} </p>
<p> City: {{ registerForm.get('address.city')?.value }}</p>
<p>Email: {{ registerForm.get('email')?.value }}</p>
</div>
</div>
registration-form.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.css']
})
export class RegistrationFormComponent implements OnInit {
registerForm!: FormGroup;
submitted!:boolean;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['',Validators.required],
lastName: ['', Validators.required],
address: this.formBuilder.group({
street: [],
zip: [],
city: []
}),
email: ['',[Validators.required,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(c.value) ? null : {
43
emailInvalid: {
message: "Invalid Format!"
}
};
}
Output:
44
EXERCISE-8
8b.Aim: 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.
Source Code:
book.ts
export class Book {
id!: number;
name!: string;
}
books-data.ts
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' }
];
book.service.ts
import { Injectable } from '@angular/core';
import { BOOKS } from './books-data';
@Injectable({
providedIn: 'root'
})
export class BookService {
getBooks() {
return BOOKS;
}
}
book.component.ts
import { Component, OnInit } from '@angular/core';
import { Book } from './book';
45
import { BookService } from './book.service';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
books!: Book[];
constructor(private bookService: BookService) { }
getBooks() {
this.books = this.bookService.getBooks();
}
ngOnInit() {
this.getBooks();
}
}
book.component.html
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{book.id}}</span> {{book.name}}
</li>
</ul>
book.component.css
.books {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 13em;
}
.books li {
cursor: pointer;
position: relative;
left: 0;
background-color: #eee;
46
margin: 0.5em;
padding: 0.3em 0;
height: 1.5em;
border-radius: 4px;
}
.books li:hover {
color: #607d8b;
background-color: #ddd;
left: 0.1em;
}
app.component.html
<app-book></app-book>
Output:
47
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
data!: Observable<number>;
myArray: number[] = [];
errors!: boolean;
finished!: boolean;
fetchData(): void {
this.data = new Observable(observer => {
setTimeout(() => { observer.next(11); }, 1000),
setTimeout(() => { observer.next(22); }, 2000),
setTimeout(() => { observer.complete(); }, 3000);
});
this.data.subscribe((value) => this.myArray.push(value),
error => this.errors = true,
() => this.finished = true);
}
}
Output:
48
EXERCISE-9
9a)Aim:Create a custom service called ProductService in which Http class is used to fetch data stored in the JSON files.
Source Code:
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpClientModule} from '@angular/common/http';
import { AppComponent } from './app.component';
import { BookComponent } from './book/book.component';
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent, BookComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
book.service.ts:
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 = 'http://localhost:3020/bookList';
constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> {
return this.http.get<Book[]>('http://localhost:3020/bookList').pipe(
tap((data: any) => console.log('Data Fetched:' + JSON.stringify(data))),
catchError(this.handleError));
}
49
addBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post('http://localhost:3020/addBook', book, { headers: options }).pipe(
catchError(this.handleError));
}
updateBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.put<any>('http://localhost:3020/update', book, { headers: options }).pipe(
tap((_: any) => console.log(`updated hero id=${book.id}`)),
catchError(this.handleError)
);}
deleteBook(bookId: number): Observable<any> {
const url = `${this.booksUrl}/${bookId}`;
return this.http.delete(url).pipe(
catchError(this.handleError));
}
private handleError(err: HttpErrorResponse): Observable<any> {
let errMsg = '';
return throwError(()=>errMsg);
}}
book.component.ts:
import { Component, OnInit } from '@angular/core';
import { BookService } from './book.service';
import { Book } from './book';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
title = 'Demo on HttpClientModule';
books!: Book[];
errorMessage!: string;
ADD_BOOK!: boolean;
UPDATE_BOOK!: boolean;
50
DELETE_BOOK!: boolean;
constructor(private bookService: BookService) { }
ngOnInit() {
this.getBooks();
}}
book.component.html:
<h2>{{ title }}</h2>
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{ book.id }}</span> {{ book.name }}
</li>
</ul>
<button class="btn btn-primary" (click)="ADD_BOOK = true">Add Book</button>
<button class="btn btn-primary" (click)="UPDATE_BOOK = true">Update Book</button>
<button class="btn btn-primary" (click)="DELETE_BOOK = true">Delete Book</button>
<br />
<div *ngIf="ADD_BOOK">
<table>
<tr>
<td>Enter Id of the book:</td>
<td>
<input type="number" #id />
</td>
</tr>
<br />
<tr>
<td>Enter Name of the Book:</td>
<td>
<input type="text" #name />
<br />
</td>
</tr>
<br />
<tr>
51
<td>
<button class="btn btn-primary" (click)="addBook(id.value, name.value); ADD_BOOK = false">
Add Record
</button>
</td>
</tr>
</table>
</div>
<div *ngIf="UPDATE_BOOK">
<table>
<tr>
<td>Enter Id of the book:</td>
<td>
<input type="number" #id />
</td>
</tr>
<br />
<tr>
<td>Enter Name of the Book:</td>
<td>
<input type="text" #name />
<tr>
<td>
<button class="btn btn-primary" (click)="updateBook(id.value, name.value); UPDATE_BOOK = false">
Update Record
</button>
</td>
</tr>
</table>
</div>
<br />
<div *ngIf="DELETE_BOOK">
</div>
<div class="error" *ngIf="errorMessage">{{ errorMessage }}</div>
52
Output:
EXERCISE-10
10a.Aim: Create multiple components and add routing to provide navigation between them.
Source Code:
dashboard.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Book } from '../book/book';
import { BookService } from '../book/book.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
books: Book[] = [];
constructor(
private router: Router,
private bookService: BookService) { }
ngOnInit(): void {
this.bookService.getBooks()
53
.subscribe({next:books => this.books = books.slice(1, 5)});
}
gotoDetail(book: Book): void {
this.router.navigate(['/detail', book.id]);
}
}
dashboard.component.html:
<h3>Top Books</h3>
<div class="grid grid-pad">
<div *ngFor="let book of books" (click)="gotoDetail(book)" class="col-1-4">
<div class="module book">
<h4>{{ book.name }}</h4>
</div>
</div>
</div>
dashboard.component.css :
[class*="col-"] {
float: left;
}
*:after,
*:before {
-webkit-box-sizing: border-box;
-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;
54
}
.module:hover {
background-color: #eee;
cursor: pointer;
color: #607d8b;
}
.grid-pad {
padding: 10px 0;
}
book.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, map} from 'rxjs/operators';
import { Book } from './book';
@Injectable({
providedIn:'root'
})
export class BookService {
booksUrl = 'http://localhost:3020/bookList';
private txtUrl = './assets/sample.txt';
constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> {
return this.http.get<any>(this.booksUrl, {observe:'response'}).pipe(
tap((data: any) => console.log('Data Fetched:' + JSON.stringify(data))),
catchError(this.handleError));
}
updateBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.put<any>('http://localhost:3020/update', book, { headers: options }).pipe(
tap((_: any) => console.log(`updated hero id=${book.id}`)),
catchError(this.handleError)
);
}
private handleError(err: HttpErrorResponse): Observable<any> {
55
let errMsg = '';
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('An error occurred:', err.error.message);
errMsg = err.error.message;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(`Backend returned code ${err.status}`);
errMsg = err.error.status;
}
return throwError(()=>errMsg);
}
}
book-detail.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Book } from '../book/book';
import { BookService } from '../book/book.service';
@Component({
selector: 'app-book-detail',
templateUrl: './book-detail.component.html',
styleUrls: ['./book-detail.component.css'],
})
export class BookDetailComponent implements OnInit {
book!: Book;
error!: any;
constructor(
private bookService: BookService,
private route: ActivatedRoute
){}
ngOnInit() {
this.route.paramsMap.subscribe(params => {
this.bookService.getBook(params.get('id')).subscribe((book) => {
this.book = book ?? this.book;
56
});
});
}
goBack() {
window.history.back();
}}
book-detail.component.html :
<div *ngIf="book">
<h2>{{ book.name }} details!</h2>
<div><label>id: </label>{{ book.id }}</div>
<div>
<label>name: </label> <input [(ngModel)]="book.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
book-detail.component.css:
label {
display: inline-block;
width: 3em;
margin: 0.5em 0;
color: #607d8b;
font-weight: bold;
}
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;
57
}
page-not-found.component.html:
<div>
<h1>404 Error</h1>
<h1>Page Not Found</h1>
</div>
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
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: [
RouterModule.forRoot(appRoutes) ],
exports: [
RouterModule ]
})
export class AppRoutingModule { }
app.module.ts :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
58
@NgModule({
imports: [BrowserModule, HttpClientModule, FormsModule, AppRoutingModule],
declarations: [AppComponent, BookComponent, DashboardComponent, BookDetailComponent,
PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'Tour of Books';
}
app.component.html:
<h1>{{title}}</h1>
<nav>
<a [routerLink]='["/dashboard"]' routerLinkActive="active">Dashboard</a>
<a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
</nav>
<router-outlet></router-outlet>
app.component.css:
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
body {
margin: 2em;
}
59
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
a{
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}
-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5}
styles.css :
/* You can add global styles to this file, and also import other style files */
body{
padding:10px;
}
book.component.ts:
import { Component, OnInit } from '@angular/core';
import { Book } from './book';
60
import { BookService } from './book.service';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
books!: Book[];
errorMessage!: string;
constructor(private bookService: BookService) { }
getBooks() {
this.bookService.getBooks().subscribe({
next: books => this.books = books,
error:error => this.errorMessage = <any>error
})
}
ngOnInit(): void {
this.getBooks();
}
}
book.component.html:
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{ book.id }}</span> {{ book.name }}
</li>
</ul>
<div class="error" *ngIf="errorMessage">{{ errorMessage }}</div>
Output:
61
=
10b.Aim: Consider 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 to reload the BooksComponent page, it should be redirected to LoginComponent. The output
is as shown below.
Source Code:
login.component.html:
<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>
login.component.ts:
62
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginService } from './login.service';
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent {
invalidCredentialMsg!: string;
loginForm!: FormGroup;
constructor(
private loginService: LoginService,
private router: Router,
private formbuilder: FormBuilder
) {}
onFormSubmit(): void {
const uname = this.loginForm.value.username;
const pwd = this.loginForm.value.password;
this.loginService
.isUserAuthenticated(uname, pwd)
.subscribe({next:(authenticated) => {
if (authenticated) {
this.router.navigate(['/books']);
} else {
this.invalidCredentialMsg = 'Invalid Credentials. Try again.';
}
}});
}
}
login.service.ts:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from './user';
63
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 this.getAllUsers().pipe(
map(users => {
const Authenticateduser = users.find(user => (user.username === username) && (user.password ===
password));
if (Authenticateduser) {
this.isloggedIn = true;
} else {
this.isloggedIn = false;
}
return this.isloggedIn;
})
);
}
isUserLoggedIn(): boolean {
return this.isloggedIn;
}
}
login-guard.service:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
64
import { LoginService } from './login.service';
@Injectable({
providedIn: 'root'
})
export class LoginGuardService implements CanActivate {
constructor(private loginService: LoginService, private router: Router) { }
canActivate(): boolean {
if (this.loginService.isUserLoggedIn()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
app.module.ts:
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 './app.component';
import { BookComponent } from './book/book.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule, AppRoutingModule],
declarations: [AppComponent, LoginComponent, BookComponent, DashboardComponent, BookDetailComponent,
PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const appRoutes: Routes = [
65
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'books', component: BookComponent , canActivate:[LoginGuardService] },
{ path: 'detail/:id', component: BookDetailComponent },
{path: 'login',component:LoginComponent},
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
Output:
66
10c.Aim: Apply lazy loading to BookComponent. If lazy loading is not added to the demo, it has loaded in 1.14 s.
Observe the load time at the bottom of the browser console. Press F12 in the browser and click the Network tab and check
the Load time.
Source Code:
book-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book.component';
import { LoginGuardService } from '../login/login-guard.service';
const bookRoutes: Routes = [
{
path: '',
component: BookComponent,
canActivate: [LoginGuardService]
}
];
@NgModule({
imports: [RouterModule.forChild(bookRoutes)],
exports: [RouterModule]
})
export class BookRoutingModule { }
book.module.ts:
67
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BookComponent } from './book.component';
import { BookRoutingModule } from './book-routing.module';
@NgModule({
imports: [CommonModule, BookRoutingModule],
declarations: [BookComponent]
})
export class BookModule { }
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'books', loadChildren: () => import('./book/book.module').then(m => m.BookModule) },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent} ,
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
68
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule, AppRoutingModule],
declarations: [AppComponent, LoginComponent, DashboardComponent, BookDetailComponent,
PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
69
import { AppRoutingModule } from './app-routing.module';
import { LoginComponent } from './login/login.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule, AppRoutingModule],
declarations: [AppComponent, LoginComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'books', loadChildren: () => import('./book/book.module').then(m => m.BookModule) },
{ path: '**', component: PageNotFoundComponent }];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes) ],
exports: [
RouterModule ]
})
export class AppRoutingModule { }
app.component.html:
<h1>{{title}}</h1>
<nav>
<a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
<a [routerLink]='["/books/dashboard"]' routerLinkActive="active">Dashboard</a>
</nav>
<router-outlet></router-outlet>
book-routing.module.ts:
import { NgModule } from '@angular/core';
70
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book.component';
import { LoginGuardService } from '../login/login-guard.service';
import { DashboardComponent } from '../dashboard/dashboard.component';
import { BookDetailComponent } from '../book-detail/book-detail.component';
const bookRoutes: Routes = [
{
path: '',
component: BookComponent,
children: [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent }
],
canActivate: [LoginGuardService]
}];
@NgModule({
imports: [RouterModule.forChild(bookRoutes)],
exports: [RouterModule]
})
export class BookRoutingModule { }
book.component.html:
<br/>
<h2>MyBooks</h2>
<ul class="books">
<li *ngFor="let book of books " (click)="gotoDetail(book)">
<span class="badge">{{book.id}}</span> {{book.name}}
</li>
</ul>
<div>
<router-outlet></router-outlet>
</div>
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
book.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
71
import { Book } from './book';
import { BookService } from './book.service';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
books: Book[]=[];
errorMessage!: string;
constructor(private bookService: BookService, private router: Router) { }
getBooks() {
this.bookService.getBooks().subscribe({
next: books => {console.log(books);this.books = books},
error:error => this.errorMessage = <any>error
})
}
gotoDetail(book: Book): void {
this.router.navigate(['/books/detail/', book.id]);
}
ngOnInit(): void {
this.getBooks();
}
}
book-detail.component.html :
<div *ngIf="book">
<h2>{{ book.name }} details!</h2>
<div><label>id: </label>{{ book.id }}</div>
<div>
<label>name: </label> <input [(ngModel)]="book.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
book-detail.component.ts :
import { Component, OnInit } from '@angular/core';
72
import { ActivatedRoute } from '@angular/router';
import { Book } from '../book/book';
import { BookService } from '../book/book.service';
@Component({
selector: 'app-book-detail',
templateUrl: './book-detail.component.html',
styleUrls: ['./book-detail.component.css'],
})
export class BookDetailComponent implements OnInit {
book!: Book;
error!: any;
constructor(
private bookService: BookService,
private route: ActivatedRoute
){}
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.bookService.getBook(params.get('id')).subscribe((book) => {
this.book = book ?? this.book
}
goBack() {
window.history.back();
}
dashboard.component.html:
<h3>Top Books</h3>
<div class="grid grid-pad">
<div *ngFor="let book of books" (click)="gotoDetail(book)" class="col-1-4">
<div class="module book">
<h4>{{ book.name }}</h4>
</div>
</div>
</div>
dashboard.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
73
import { Book } from '../book/book';
import { BookService } from '../book/book.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
books: Book[] = [];
constructor(
private router: Router,
private bookService: BookService) { }
ngOnInit(): void {
this.bookService.getBooks()
.subscribe(books => this.books = books.slice(1, 5));
}
gotoDetail(book: Book): void {
this.router.navigate(['/books/detail', book.id]);
}
}
Output:
74
EXERCISE-11
Steps:-
Step 2: When the download is complete open the msi file and click the next button in the startup screen:
Step 3: Now accept the End-User License Agreement and click the next button:
Step 4: Now select the complete option to install all the program features. Here, if you can want to install only selected
program features and want to select the location of the installation, then use the Custom option:
75
Step 5: Select “Run service as Network Service user” and copy the path of the data directory. Click Next:
76
Step 8: Now click the Finish button to complete the installation process:
Step 9: Now we go to the location where MongoDB installed in step 5 in your system and copy the bin path:
Step 10: Now, to create an environment variable open system properties << Environment Variable << System variable
<< path << Edit Environment variable and paste the copied link to your environment system and click Ok:
77
Step 11: After setting the environment variable, we will run the MongoDB server, i.e. mongod. So, open the command
prompt and run the following command:
CONFIGURING ATLAS:
78
2. Sign in or create a new account.
3. Create a new project.
9. Click on "Network Access" to whitelist your IP address to allow connections to your cluster.
79
10. In the "Clusters" view, click "Connect" and choose "Connect Your Application."
11b.Aim: Write MongoDB queries to perform CRUD operations on document using insert(), find(), update(), remove().
Source Code:
Insert():
Deprecated Method: insert() is deprecated in recent MongoDB versions. It is recommended to use
insertOne(), insertMany(), or bulkWrite() for inserting documents.
Insert Single Document: Use insertOne() to insert a single document into a collection.
Insert Multiple Documents: Use insertMany() to insert an array of documents into a collection.
80
Find():
Retrieve Documents: Use find() to retrieve documents from a collection.
Find All Documents: find() without a query parameter returns all documents in the collection.
Query Conditions: You can use query conditions to filter documents based on specific criteria.
Update():
Deprecated Method: update() is deprecated. Instead, use updateOne(), updateMany(), or bulkWrite() for
updating documents.
Update Single Document: Use updateOne() to update a single document that matches a specified filter.
Update Multiple Documents: Use updateMany() to update multiple documents that match a specified
filter.
81
Remove():
Deprecated Method: remove() is deprecated. Use deleteOne(), deleteMany(), findOneAndDelete(), or
bulkWrite() for removing documents.
Delete Single Document: Use deleteOne() to remove a single document that matches a specified filter.
Delete Multiple Documents: Use deleteMany() to remove multiple documents that match a specified
filter.
Remove All Documents: To remove all documents in a collection, use deleteMany({}).
82
EXERCISE-12
12a.Aim: Write MongoDB queries to Create and drop databases and collections.
Source code:
Create Database:
o Use the use command followed by the desired database name to create a new database.
Drop (Delete) Database:
o Use db.getSiblingDB("myDatabase").dropDatabase() to delete the specified database.
o Exercise caution, as dropping a database permanently deletes all its data.
Create Collection:
o Switch to the desired database using the use command.
o Use db.createCollection("myCollection") to create a new collection within the selected database.
Drop (Delete) Collection:
o Use db.getSiblingDB("myDatabase").myCollection.drop() to delete the specified collection within the
database.
83
12b.Aim: Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(), aggregate().
Source code:
Find():
Usage Example:
limit():
sort():
createIndex():
aggregate():
$group: {
_id: "$city",
}}])
84
85