[go: up one dir, main page]

0% found this document useful (0 votes)
12 views88 pages

Exp No: Page No: Date

Uploaded by

Rosy
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)
12 views88 pages

Exp No: Page No: Date

Uploaded by

Rosy
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
You are on page 1/ 88

Exp No: Page No:

Date:

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.
Aim: To display the product code in lowercase and product name in uppercase using built-in
pipes.
Description:
Pipes provide a beautiful way of transforming the data inside templates, for the purpose of
display. Pipes in Angular take an expression value as an input and transform it into the
desired output before displaying it to the user. It provides a clean and structured code as you
can reuse the pipes throughout the application, while declaring each pipe just once.
Syntax: {{ expression | pipe }}
Uppercase:This pipe converts the template expression into uppercase.
Syntax:{{ expression | uppercase }}
Lowercase:This pipe converts the template expression into lowercase.
Syntax: {{ expression | lowercase }}
Titlecase:This pipe converts the first character in each word of the given expression into a
capital letter.
Syntax: {{ expression | titlecase }}
Program:
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>
<th> Product Code </th>
<td> {{ productCode | lowercase }} </td>
</tr>
<tr>
<th> Product Name </th>
<td> {{ productName | uppercase }} </td>
</tr>
</table>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
5.b Course Name: Angular JS
Module Name: Passing Parameters to Pipes
Apply built-in pipes with parameters to display product details.
Aim: To apply built-in pipes with parameters to display product details.
Description:
A pipe can also have optional parameters to change the output. To pass parameters, after a
pipe name add a colon( : ) followed by the parameter value.
pipename : parametervalue
This pipe displays a currency symbol before the expression. By default, it displays the
currency symbol $
{{ expression | currency:currencyCode:symbol:digitInfo:locale }}
Program:
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> 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>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<tr>
<th> Product Tax </th>
<td> {{ productTax | percent : '.2' }} </td>
</tr>
<tr>
<th> Product Rating </th>
<td>{{ productRating | number:'1.3-5'}} </td>
</tr>
</table>
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,
],
imports: [
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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.

Aim: To load CourseslistComponent in the root component when a user clicks on the View
courses list button.

Description:
Nested component is a component that is loaded into another component
The component where another component is loaded onto is called a container
component/parent component.
The root component is loaded in the index.html page using its selector name. Similarly, to
load one component into a parent component, use the selector name of the component in the
template i.e., the HTML page of the container component.

Program:

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';


import { CourseListComponent } from './course-list/course-
list.component';
@NgModule({
declarations: [
AppComponent,
CourseListComponent,
],
imports: [
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
course-list.component.ts:
import { Component } from '@angular/core';

@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
export class CourseListComponent {

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
courses = [
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
}
course.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.courseId }}</td>
<td>{{ course.courseName }}</td>
</tr>
</tbody>
</table>
course-list.component.css:
tr{
text-align:center;
}
app.component.html:
<h2>Popular Courses</h2>
<button (click)="show = true">View Courses list</button><br
/><br />
<div *ngIf="show">
<app-course-list></app-course-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;
title: any;
}

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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 dropdown, corresponding course details should be loaded.

Aim: To 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 dropdown, corresponding course details should be loaded.

Description: Component communication is needed if data needs to be shared between the


components In order to pass data from container/parent component to child component,
@Input decorator can be used. A child component can use @Input decorator on any property
type like arrays, objects, etc. making it a data-bound input property. The parent component
can pass value to the data-bound input property when rendering the child within it.

Program:

courses-list.component.ts:
import { Component, Input } from '@angular/core';

@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
export class CourseListComponent {
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]);
}
}
}
}

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
course-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>{{c.courseId}}</td>
<td>{{c.courseName}}</td>
</tr>
</tbody>
</table>

app.component.html:
<h2>Course Details</h2>
Select a course to view
<select #course (change)="name = course.value">
<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>

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;
}

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

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 the register button, it should send that courseName value back to
AppComponent where it should display the registration successful message along with
courseName.

Aim: To create an AppComponent that loads another component called the CoursesList
Component.

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

Description:
If a child component wants to send data to its parent component, then it must create a
property with @Output decorator.
The only method for the child component to pass data to its parent component is through
events. The property must be of type EventEmitter.

Program:
course-list.compnent.ts
import { Component,OnInit, Input,Output, EventEmitter } from
'@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-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' },
];
registerEvent: any;
register(courseName:string){
this.registerEvent.emit(courseName);
}
}

course-list.component.html
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th></th>
</tr>
</thead>

<tbody>
<tr *ngFor="let course of courses">
<td>{{ course.courseId }}</td>
<td>{{ course.courseName }}</td>
<td><button
(click)="register(course.courseName)">Register</button></td>
</tr>
</tbody>
</table>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
app.component.html
<h2>Courses List</h2>
<app-courses-list (registerEvent)="courseReg($event)"></app-
courses-list>
<br /><br />
<div *ngIf="message">{{ message }}</div>

app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
message!: string;
courseReg(courseName: string) {
this.message = `Your registration for ${courseName} is
successful`;
}
}

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

6.c Course Name: Angular JS


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

Aim: To apply ShadowDOM and Nonr encapsulation modes to components.

Description:
Shadow DOM is a web components standard by W3C. It enables encapsulation for
DOM tree and styles. Shadow DOM hides DOM logic behind other elements and confines
styles only for that component.
ViewEncapsulation.ShadowDOM enables Angular to use the browser's native
Shadow DOM implementation. This mode is introduced in version 7.

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Angular doesn’t use shadow DOM in ViewEncapsulation.None.All the styles
defined in a component is applied to the entire document. i.e., a component can overwrite
another component’s styles. This is an unscoped strategy.

Program:

ViewEncapsulation.ShadowDOM:
Create a component first using ng generate component first

First.component.css:
.cmp {
padding: 6px;
margin: 6px;
border: blue 2px solid;
}
First.component.html:
<div class="cmp">First Component</div>

Now generate another component with name Second using ng generate second

Second.component.css
.cmp {
border: green 2px solid;
padding: 6px;
margin: 6px;
}
Second.component.html
<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 {

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
}

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>

Output:

ViewEncapsulation.None
App.component.ts:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html',
encapsulation: ViewEncapsulation.None
})
export class AppComponent {
}
Second.component.ts:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css'],
encapsulation: ViewEncapsulation.None
})
export class SecondComponent {
}
Output:

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.

Aim:To override component life-cycle hooks and logging the corresponding messages to
understand the flow.

Description:
A component has a life cycle that is managed by Angular. It includes creating a component,
rendering it, creating and rendering its child components, checks when its data-bound
properties change, and destroy it before removing it from the DOM.

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
ngOnChanges – It gets invoked when Angular sets data-bound input property i.e., the
property attached with @Input(). This will be invoked whenever input property changes its
value
ngOnInit – It gets invoked when Angular initializes the directive or component
ngDoCheck - It will be invoked for every change detection in the application
ngAfterContentInit – It gets invoked after Angular projects content into its view
ngAfterContentChecked – It gets invoked after Angular checks the bindings of the content
it projected into its view
ngAfterViewInit – It gets invoked after Angular creates component’s views
ngAfterViewChecked – It gets invoked after Angular checks the bindings of the
component’s views
– It gets invoked before Angular destroys directive or component

Program:

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');
}
ngAfterViewChecked(): void {
console.log('After view checked');
}

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
ngOnDestroy(): void {
console.log('Destroy');
}
}

app.component.html:
<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]="data" />
<app-child [title]="data"></app-child>
</div>
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));
}
}

child.component.html:
<h2>Child Component</h2>
<h2>{{title}}</h2>

app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ChildComponent } from './child/child.component';
import { } from './app.component';
@NgModule({
declarations: [
AppComponent,
ChildComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent],

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
})
export class AppModule { }

Output:

7a) Course Name: Angular JS

Module Name: Template Driven Forms

Create a course registration form as a template-driven form.

Aim: To create a course registration form as a template-driven form.

Description:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Template-driven forms are the forms that are created using Angular template syntax. In
template-driven form, data binding, validation, etc., will be written in the template itself.

create a component called CourseFormComponent using the following command

D:\devi>ng generate component courseForm

Program:

course.ts:

export class Course {

constructor(

public courseId: number,

public courseName: string,

public duration: string

){}

course-form.component.ts:

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

import { Course } from './course';

@Component({

selector: 'app-course-form',

templateUrl: './course-form.component.html',

styleUrls: ['./course-form.component.css']

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
})

export class CourseFormComponent {

course = new Course(1, 'Angular', '5 days');

submitted = false;

onSubmit() { this.submitted = true; }

Install Boostrap

D:\devi>npm install bootstrap@3.3.7 --save

angular.json :

"styles": [

"styles.css",

"./node_modules/bootstrap/dist/css/bootstrap.min.css"

],

course-form.component.html :

<div class="container">

<div [hidden]="submitted">

<h1>Course Form</h1>

<form (ngSubmit)="onSubmit()" #courseForm="ngForm">

<div class="form-group">

<label for="id">Course Id</label>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<input type="text" class="form-control" required [(ngModel)]="course.courseId"
name="id" #id="ngModel">

<div [hidden]="id.valid || id.pristine" class="alert alert-danger">

Course Id is required

</div>

</div>

<div class="form-group">

<label for="name">Course Name</label>

<input type="text" class="form-control" required [(ngModel)]="course.courseName"


name="name" #name="ngModel">

<div [hidden]="name.valid || name.pristine" class="alert alert-danger">

Course Name is required

</div>

</div>

<div class="form-group">

<label for="duration">Course Duration</label>

<input type="text" class="form-control" required [(ngModel)]="course.duration"


name="duration" #duration="ngModel">

<div [hidden]="duration.valid || duration.pristine" class="alert alert-danger">

Duration is required

</div>

</div>

<button type="submit" class="btn btn-default" [disabled]="!


courseForm.form.valid">Submit</button>

<button type="button" class="btn btn-default" (click)="courseForm.reset()">New


Course</button>

</form>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
</div>

<div [hidden]="!submitted">

<h2>You submitted the following:</h2>

<div class="row">

<div class="col-xs-3">Course ID</div>

<div class="col-xs-9 pull-left">{{ course.courseId }}</div>

</div>

<div class="row">

<div class="col-xs-3">Course Name</div>

<div class="col-xs-9 pull-left">{{ course.courseName }}</div>

</div>

<div class="row">

<div class="col-xs-3">Duration</div>

<div class="col-xs-9 pull-left">{{ course.duration }}</div>

</div>

<br>

<button class="btn btn-default" (click)="submitted=false">Edit</button>

</div>

</div>

course-form.component.css:

input.ng-valid[required] {

border-left: 5px solid #42A948; /* green */

input.ng-dirty.ng-invalid:not(form) {

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
border-left: 5px solid #a94442; /* red */

app.component.html:

<app-course-form></app-course-form>

app.module.ts:

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

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

import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { CourseFormComponent } from './course-form/course-form.component';

@NgModule({

declarations: [

AppComponent,

CourseFormComponent

],

imports: [

BrowserModule,

FormsModule

],

providers: [],

bootstrap: [AppComponent]

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
})

export class AppModule { }

Output:

When Clicked on Submit Button it displays like this:

When clicked on edit we can change the details like this:

When clicked on New Course Button it displays like this:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

7b) Course Name: Angular JS

Module Name: Model Driven Forms or Reactive Forms

Create an employee registration form as a reactive form.

Aim: To create an employee registration form as a reactive form.

Description:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
In reactive forms, you can control the form completely from the component class and hence
you will get direct, explicit access to the underlying forms object model. Hence, reactive
forms are also known as 'model-driven forms'. As reactive forms are more robust and
scalable, they are more suitable for creating all kind of forms in an application, irrespective of
the size of form.

Program:

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: [],

bootstrap: [AppComponent]

})

export class AppModule { }

Create a Component:

Command:ng generate component RegistrationForm

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Install Bootstrap:

Command: npm install bootstrap@3.3.7 --save

angular.json:

"styles": [

"src/styles.css",

"node_modules/bootstrap/dist/css/bootstrap.min.css"

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],

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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">

Firstname field is invalid.

<p
*ngIf="registerForm.controls['firstName'].errors?.
['required']">

This field is required!

</p>

</div>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
</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">

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

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>

</form>

<br/>

<div [hidden]="!submitted">

<h3> Employee Details </h3>

<p>First Name:
{{ registerForm.get('firstName')?.value }} </p>

<p> Last Name: {{ registerForm.get('lastName')?.value }}


</p>

<p> Street: {{ registerForm.get('address.street')?.value


}}</p>

<p> Zip: {{ registerForm.get('address.zip')?.value }}


</p>

<p> City:
{{ registerForm.get('address.city')?.value }}</p>

</div>

</div>

registration-form.component.css:

.ng-valid[required] {

border-left: 5px solid #42A948; /* green */

.ng-invalid:not(form) {

border-left: 5px solid #a94442; /* red */

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
app.component.html:

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

Output:

Before Filling the Form:

After Filling the Form:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

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

Aim: To Create a custom validator for an email field in the employee registration form
(reactive form).

Description:

Custom validation in Reactive Forms of Angular:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Custom validation can be applied to form controls of a Reactive Form in Angular.

Custom validators are implemented as separate functions inside the component.ts file.

these functions can be added to the list of other validators configured for a form control.

Program:

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],

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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 : {

emailInvalid: {

message: "Invalid Format!"

};

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">

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<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">

<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">

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
</fieldset>

</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/>

<div [hidden]="!submitted">

<h3> Employee Details </h3>

<p>First Name: {{ registerForm.get('firstName')?.value }} </p>

<p> Last Name: {{ registerForm.get('lastName')?.value }} </p>

<p> Street: {{ registerForm.get('address.street')?.value }}</p>

<p> Zip: {{ registerForm.get('address.zip')?.value }} </p>

<p> City: {{ registerForm.get('address.city')?.value }}</p>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<p>Email: {{ registerForm.get('email')?.value }}</p>

</div>

</div>

Output:

Before Filling the Form:

After Filling the Form:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

8a) Course Name: Angular JS

Module Name: Custom Validators in Template Driven forms

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Create a custom validator for the email field in the course registration form.

Aim: To Create a custom validator for the email field in the course registration form.

Description:

Program:

While creating forms, there can be situations for validations for which built-in validators are
not available. Few such examples include validating a phone number, validating if the
password and confirm password fields matches or not, etc., In such situations, we can create
custom validators to implement the required functionality.

course.ts:

export class Course {

constructor(

public courseId: number,

public courseName: string,

public duration: string,

public email: string

){}

course-form.component.ts:

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

import { Course } from './course';

@Component({

selector: 'app-course-form',

templateUrl: './course-form.component.html',

styleUrls: ['./course-form.component.css']

})

export class CourseFormComponent {

course: Course = new Course(1, 'Angular 2', '4 days', 'devikan4353@gmail.com');

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
submitted = false;

onSubmit() { this.submitted = true; }

email.validator.ts:

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

import { NG_VALIDATORS, FormControl, Validator } from '@angular/forms';

@Directive({

selector: '[validateEmail]',

providers: [

{ provide: NG_VALIDATORS, useExisting: EmailValidator, multi: true },

],

})

export class EmailValidator implements Validator {

validate(control: FormControl): any {

const emailRegexp =

/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;

if (!emailRegexp.test(control.value)) {

return { emailInvalid: 'Email is invalid' };

return null;

app.module.ts:

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

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

import { FormsModule } from '@angular/forms';

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
import { AppComponent } from './app.component';

import { CourseFormComponent } from './course-form/course-form.component';

import { EmailValidator } from './course-form/email.validator';

@NgModule({

declarations: [

AppComponent,

CourseFormComponent,

EmailValidator

],

imports: [

BrowserModule,

FormsModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

course-form.component.html:

<div class="container">

<div [hidden]="submitted">

<h1>Course Form</h1>

<form (ngSubmit)="onSubmit()" #courseForm="ngForm">

<div class="form-group">

<label for="id">Course Id</label>

<input type="text" class="form-control" required [(ngModel)]="course.courseId"


name="id" #id="ngModel">

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<div [hidden]="id.valid || id.pristine" class="alert alert-danger">

Course Id is required</div>

</div>

<div class="form-group">

<label for="name">Course Name</label>

<input type="text" class="form-control" required [(ngModel)]="course.courseName"

minlength="4" name="name" #name="ngModel">

<div *ngIf="name.errors && (name.dirty || name.touched)" class="alert alert-


danger">

<div [hidden]="!name.errors['required']">Name is required</div>

<div [hidden]="!name.errors['minlength']">Name must be at least 4 characters


long.</div>

</div>

</div>

<div class="form-group">

<label for="duration">Course Duration</label>

<input type="text" class="form-control" required [(ngModel)]="course.duration"

name="duration" #duration="ngModel">

<div [hidden]="duration.valid || duration.pristine" class="alert alert-


danger">Duration is required</div>

</div>

<div class="form-group">

<label for="email">Author Email</label>

<input type="text" class="form-control" required [(ngModel)]="course.email"

name="email" #email="ngModel" validateEmail>

<div *ngIf="email.errors && (email.dirty || email.touched)" class="alert alert-


danger">

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<div [hidden]="!email.errors['required']">Email is required</div>

<div [hidden]="!email.errors['emailInvalid']">{{email.errors['emailInvalid']}}</div>

</div>

</div>

<button type="submit" class="btn btn-default" [disabled]="!


courseForm.form.valid">Submit</button>

<button type="button" class="btn btn-default" (click)="courseForm.reset()">New


Course</button>

</form>

</div>

<div [hidden]="!submitted">

<h2>You submitted the following:</h2>

<div class="row">

<div class="col-xs-3">Course ID</div>

<div class="col-xs-9 pull-left">{{ course.courseId }}</div>

</div>

<div class="row">

<div class="col-xs-3">Course Name</div>

<div class="col-xs-9 pull-left">{{ course.courseName }}</div>

</div>

<div class="row">

<div class="col-xs-3">Duration</div>

<div class="col-xs-9 pull-left">{{ course.duration }}</div>

</div>

<div class="row">

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<div class="col-xs-3">Email</div>

<div class="col-xs-9 pull-left">{{ course.email }}</div>

</div>

<br>

<button class="btn btn-default" (click)="submitted=false">Edit</button>

</div>

</div>

Output:

When Clicked on Submit it displays like this:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

When Clicked on Edit Button it displays like this:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Validating of Email is shown:

After Changing the Email The Form is Submitted.

8b) Course Name: Angular JS

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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.

Aim: To 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.

Description:

A service in Angular is a class that contains some functionality that can be reused across the
application. A service is a singleton object. Angular services are a mechanism of abstracting
shared code and functionality throughout the application.
Angular Services come as objects which are wired together using dependency injection.
Angular provides a few inbuilt services also can create custom services.
Services can be used to:
1.share the code across components of an application.
2.make HTTP requests.
Creating a Service
To create a service class, use the following command:
Command: ng generate service book

Program:

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' },

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
{ id: 3, name: 'Java Script' },

{ id: 4, name: 'Ajax Programming' },

{ id: 5, name: 'jQuery' },

{ id: 6, name: 'Mastering Node.js' },

{ id: 7, name: 'Angular JS 1.x' },

{ id: 8, name: 'Core Java' },

{ id: 9, name: 'Backbone JS' },

{ id: 10, name: 'MongoDB Basics' }

];

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';

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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;

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;

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
padding: 0.8em 0.7em 0 0.7em;

background-color: green;

line-height: 0.5em;

position: relative;

left: -1px;

top: -4px;

height: 1.8em;

margin-right: 0.8em;

border-radius: 4px 0 0 4px;

app.component.html:

<app-book></app-book>

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

8c) Course Name: Angular JS

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Module Name: RxJS Observables

Create and use an observable in Angular.

Aim:To create and use an observable in Angular.

Description:

RxJS
Reactive Extensions for JavaScript (RxJS) is a third-party library used by the Angular team.
RxJS is a reactive streams library used to work with asynchronous streams of data.
Observables, in RxJS, are used to represent asynchronous streams of data. Observables are a
more advanced version of Promises in JavaScript
Program:

app.component.ts:

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

import { Observable } from 'rxjs';

@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(43); }, 1000),

setTimeout(() => { observer.next(54); }, 2000),

setTimeout(() => { observer.complete(); }, 3000);

});

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
this.data.subscribe((value) => this.myArray.push(value),

error => this.errors = true,

() => this.finished = true);

app.component.html:

<b> Using Observables In Angular!</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:

9a) Course Name: Angular JS

Module Name: Server Communication using HttpClient

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
Create an application for Server Communication using HttpClient .

Aim: To Create an application for Server Communication using HttpClient .

Description:

 Most front-end applications communicate with backend services using HTTP Protocol

 While making calls to an external server, the users must continue to be able to interact
with the page. That is, the page should not freeze until the HTTP request returns from the
external server. So, all HTTP requests are asynchronous.

 HttpClient from @angular/common/http to communicate must be used with backend


services.

 Additional benefits of HttpClient include testability features, typed request and response
objects, request and response interception, Observable APIs, and streamlined error
handling.

 HttpClientModule must be imported from @angular/common/http in the module class to


make HTTP service available to the entire module. Import HttpClient service class into a
component’s constructor. HTTP methods like get, post, put, and delete are made used
off.

 JSON is the default response type for HttpClient


Program:

Backend Environment Creation:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

Program:

app.js:

var express = require('express');

var router = require('./routes/index');

var cors = require('cors');

var app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.json())

app.use(bodyParser.urlencoded({ extended: true }));

app.use(function (req, res, next) {

res.header("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Methods",
"GET,HEAD,OPTIONS,POST,PUT,DELETE");

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-


With, Content-Type, Accept, x-client-key, x-client-token, x-client-
secret, Authorization");

next();

});

app.use(cors())

app.options('*', cors())

app.use('/', router);

app.listen(3020, function () {

console.log('Server is up and running...');

});

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

books.json:

"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 Node.js"

},

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
{

"id": 7,

"name": "Angular JS 1.x"

},

"id": 8,

"name": "ng-book 2"

},

"id": 9,

"name": "Backbone JS"

},

"id": 10,

"name": "Yeoman"

index.js:

var express = require('express');

var bookList = [{ "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 Node.js" },

{ "id": 7, "name": "Angular JS 1.x" },

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
{ "id": 8, "name": "ng-book 2" },

{ "id": 9, "name": "Backbone JS" },

{ "id": 10, "name": "Yeoman" }

var router = express.Router();

var path = require('path');

router.get('/', function (req, res, next) {

console.log("hi")

})

//API : http://localhost:3020/addBook

router.post('/addBook', function (req, res) {

res.setHeader("Access-Control-Allow-Origin", "*");

res.setHeader("Access-Control-Allow-Credentials", "true");

res.setHeader("Access-Control-Allow-Methods", "POST, GET,


OPTIONS, DELETE");

res.setHeader("Access-Control-Allow-Headers", "Content-Type,
Accept, X-Requested-With, remember-me");

var body = req.body;

bookList.push(body)

res.json(body);

});

//API : http://localhost:3020/bookList/:id

router.delete('/bookList/:id', function (req, res) {

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
var id = req.params.id

var index = bookList.findIndex(book => book.id == id)

bookList.splice(index, 1);

res.json(bookList);

});

//API : http://localhost:3020/bookList

router.get('/bookList', function (req, res) {

res.setHeader("Access-Control-Allow-Origin", "*");

res.setHeader("Access-Control-Allow-Origin", "*");

res.json(bookList);

});

//API : http://localhost:3020/update

router.put('/update', function (req, res) {

var obj = bookList.findIndex(book => book.id == req.body.id)

bookList[obj] = req.body

res.json(bookList);

});

module.exports = router;

FrontEnd Code:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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;

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: green;

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
line-height: 0.5em;

position: relative;

left: -1px;

top: -4px;

height: 1.8em;

margin-right: 0.8em;

border-radius: 4px 0 0 4px;

book.component.html:

<h2>{{ title }}</h2>

<h2>Books List</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>&nbsp;

<button class="btn btn-primary" (click)="UPDATE_BOOK = true">Update


Book</button>&nbsp;

<button class="btn btn-primary" (click)="DELETE_BOOK = true">Delete


Book</button>

<br />

<br/>

<div *ngIf="ADD_BOOK">

<table>

<tr>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<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>

<td>

<button class="btn btn-primary" (click)="addBook(id.value,


name.value); ADD_BOOK = false">

Add Record

</button>

</td>

</tr>

</table>

<br />

</div>

<div *ngIf="UPDATE_BOOK">

<table>

<tr>

<td>Enter Id of the book:</td>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<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>

<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">

<table>

<tr>

<td>Enter Id of the book:</td>

<td>

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
<input type="number" #id />

</td>

</tr>

<br />

<tr>

<td>

<button class="btn btn-primary"


(click)="deleteBook(id.value); DELETE_BOOK = false">

Delete Record

</button>

</td>

</tr>

</table>

</div>

<div class="error" *ngIf="errorMessage">{{ errorMessage }}</div>

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 = ' Server Communication using HttpClient ';

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
books!: Book[];

errorMessage!: string;

ADD_BOOK!: boolean;

UPDATE_BOOK!: boolean;

DELETE_BOOK!: boolean;

constructor(private bookService: BookService) { }

getBooks() {

this.bookService.getBooks().subscribe({

next: books => this.books = books,

error:error => this.errorMessage = <any>error

})

addBook(bookId: string, name: string): void {

let id=parseInt(bookId)

this.bookService.addBook({id, name })

.subscribe({next:(book: any) => this.books.push(book)});

updateBook(bookId: string, name: string): void {

let id=parseInt(bookId)

this.bookService.updateBook({ id, name })

.subscribe({next:(book: any) => this.books = book});

deleteBook(bookId: string): void {

let id=parseInt(bookId)

this.bookService.deleteBook(id)

.subscribe({next:(book: any) => this.books = book});

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
ngOnInit() {

this.getBooks();

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));

addBook(book: Book): Observable<any> {

const options = new HttpHeaders({ 'Content-Type':


'application/json' });

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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 = '';

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.

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
// 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.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' },

{ id: 6, name: 'Mastering Node.js' },

{ id: 7, name: 'Angular JS 1.x' },

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
{ id: 8, name: 'Core Java' },

{ id: 9, name: 'Backbone JS' },

{ id: 10, name: 'MongoDB Basics' }

];

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 { }

app.component.html:

<app-book></app-book>

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
9b) Course Name: Angular JS

Module Name: Communicating with different backend services using Angular


HttpClient

Create a custom service called ProductService in which Http class is used to fetch data
stored in the JSON files.

Aim: To Create a custom service called ProductService in which Http class is used to fetch
data stored in the JSON files.

Description:

Communicating with different backend services using Angular HttpClient


Angular can also be used to connect to different services written in different
technologies/languages. For example, we can make a call from Angular to Node/Express or
Java or Mainframe or .Net services, etc.
Program:

mobiles.json:

"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

},

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
"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

tablets.json :

"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

},

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
"productId": 2,

"productName": "Apple iPad Air2",

"productCode": "TAB-124",

"description": "64GB, Black",

"price": 600,

"imageUrl": "assets/imgs/ipad_air.jpg",

"manufacturer": "Apple",

"ostype": "iOS",

"rating": 3

product.service.ts:

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

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
constructor(private http: HttpClient) {

if (sessionStorage.getItem('selectedProducts')) {

this.selectedProducts = JSON.parse(sessionStorage.getItem('selectedProducts') + '');

// Makes a get request to backend to fetch products data

getProducts(): Observable<Product[]> {

if (this.producttype === 'tablet') {

return this.http.get<Product[]>('./assets/products/tablets.json').pipe(

tap((products) => this.products = products),

catchError(this.handleError));

} else if (this.producttype === 'mobile') {

return this.http.get<Product[]>('./assets/products/mobiles.json').pipe(

tap((products) => this.products = products),

catchError(this.handleError));

else

throw new Error();

// Fetches the selected product details

getProduct(id: number): Observable<Product> {

return this.getProducts().pipe(

map(products => products.filter(product => product.productId === id)[0]));

// Error Handling code

private handleError(err: HttpErrorResponse) {

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
return throwError(() => err.error() || 'Server error');

products.module.ts:

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

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

import { FormsModule } from '@angular/forms';

import { ProductsRoutingModule } from './products-routing.module';

import { ProductListComponent } from './product-list/product-list.component';

import { ProductDetailComponent } from './product-detail/product-detail.component';

import { CartComponent } from './cart/cart.component';

import { OrderByPipe } from './product-list/orderby.pipe';

import { RatingComponent } from './rating.component';

import { ProductService } from './product.service';

import { AuthGuardService } from './auth-guard.service';

@NgModule({

imports: [

CommonModule,

FormsModule,

ProductsRoutingModule

],

declarations:
[ProductListComponent,ProductDetailComponent,CartComponent,OrderByPipe,RatingCo
mponent],

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
providers:[ProductService,AuthGuardService]

})

export class ProductsModule { }

product-list.component.ts:

import { AfterViewInit, Component, ElementRef, OnInit, Renderer2, ViewChild } from


'@angular/core';

import { ProductService } from '../product.service';

import { Cart } from '../cart/Cart';

import { Product } from '../product';

import { LoginService } from 'src/app/login/login.service';

@Component({

templateUrl: 'product-list.component.html',

styleUrls: ['product-list.component.css']

})

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 = '';

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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 = '';

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
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() {

this.loginVal = this.loginService.loginElement;

this.welcomeVal = this.loginService.welcomeElement;

this.renderer.setProperty(this.loginVal.nativeElement, 'innerText', 'Logout');

this.renderer.setStyle(this.welcomeVal.nativeElement, 'display', 'inline');

let welcomeText="Welcome "+this.loginService.username+ " ";

this.renderer.setProperty(this.welcomeVal.nativeElement, 'innerText', welcomeText);

this.renderer.setStyle(this.welcomeVal.nativeElement, 'color', '#ff0080');

ngOnInit() {

this.orderId++;

this.productService.getProducts()

.subscribe({

next:products => {

this.productService.products = products;

this.products = this.productService.products;

this.chkmanosprice =this.products

},

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
error:error => this.errorMessage = error});

if (this.productService.selectedProducts.length > 0) {

this.selectedItems = Number(sessionStorage.getItem('selectedItems'));

this.total = Number(sessionStorage.getItem('grandTotal'));

checkManufacturers(cManuf: any[], cProducts: any[], chkman: any[]) {

if (cManuf.length > 0) {

for (let checkManuf of cManuf) {

for (let checkProd of cProducts) {

if (checkProd.manufacturer.toLowerCase() === checkManuf.toLowerCase()) {

this.chkman.push(checkProd);

} else {

this.chkman = cProducts;

checkOpsystem(cOS: any[], chkman: any[], chkmanos: any[]) {

if (cOS.length > 0) {

for (let checkOS of cOS) {

for (let chkmann of chkman) {

if (chkmann.ostype.toLowerCase() === checkOS.toLowerCase()) {

this.chkmanos.push(chkmann);

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
}

} else {

this.chkmanos = chkman;

checkPrices(checkedPrice: any[], chkmanosprice: any[], chkmanos: any[]) {

if (checkedPrice.length > 0) {

for (let checkPrice of checkedPrice) {

for (let chkmanfos of chkmanos) {

if (checkPrice === '300-450') {

if (chkmanfos.price >= 300 && chkmanfos.price <= 450) {

this.chkmanosprice.push(chkmanfos);

if (checkPrice === '450-600') {

if (chkmanfos.price > 450 && chkmanfos.price <= 600) {

this.chkmanosprice.push(chkmanfos);

if (checkPrice === '600-800') {

if (chkmanfos.price > 600 && chkmanfos.price <= 800) {

this.chkmanosprice.push(chkmanfos);

if (checkPrice === '800-1000') {

if (chkmanfos.price > 800 && chkmanfos.price <= 1000) {

this.chkmanosprice.push(chkmanfos);

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
}

} else {

this.chkmanosprice = chkmanos;

// filtering functionality

filter(name: any) {

let checkedProducts: any[];

this.chkman = [];

this.chkmanos = [];

this.chkmanosprice = [];

const index = 0;

checkedProducts = this.productService.products;

name.checked = (name.checked) ? false : true;

this.checkedManufacturers = this.manufacturers.filter(product =>


product.checked).map(product => product.id);

this.checkedOS = this.os.filter(product => product.checked).map(product => product.id);

this.checkedPrice = this.price_range.filter(product => product.checked).map(product =>


product.id);

this.checkManufacturers(this.checkedManufacturers, checkedProducts, this.chkman);

this.checkOpsystem(this.checkedOS, this.chkman, this.chkmanos);

this.checkPrices(this.checkedPrice, this.chkmanosprice, this.chkmanos);

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
//this.products = [];

this.products = this.chkmanosprice;

// Invoked when user clicks on Add to Cart button

// Adds selected product details to service class variable

// called selectedProducts

addCart(id: number) {

this.cart = new Cart();

this.selectedItems += 1;

// fetching selected product details

const product = this.productService.products.filter((currProduct: any) =>


currProduct.productId === id)[0];

this.total += product.price;

sessionStorage.setItem('selectedItems', this.selectedItems);

const sp = this.productService.selectedProducts.filter((currProduct: any) =>


currProduct.productId === id)[0];

if (sp) {

const index = this.productService.selectedProducts.findIndex((currProduct: any) =>


currProduct.productId === id);

this.productService.selectedProducts[index].quantity += 1;

this.productService.selectedProducts[index].totalPrice += product.price;

} else {

this.cart.orderId = 'ORD_' + this.orderId;

this.cart.productId = id;

this.cart.userId = sessionStorage.getItem('username') + '';

this.cart.productName = product.productName;

this.cart.price = product.price;

this.cart.quantity = 1;

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
this.cart.dateOfPurchase = new Date().toString();

this.cart.totalPrice = product.price * this.cart.quantity;

this.productService.selectedProducts.push(this.cart);

sessionStorage.setItem('selectedProducts',
JSON.stringify(this.productService.selectedProducts));

this.orderId++;

// Search box functionality

// Searches based on manufacturer name

searchtext() {

this.products = this.productService.products;

if (this.listFilter.length > 0) {

this.products = this.products.filter((product: Product) =>

product.manufacturer.toLowerCase().indexOf(this.listFilter) !== -1);

// Invoked when a tab (Tablets/Mobiles) is clicked

// Displays tablets or mobiles data accordingly

tabselect(producttype: string) {

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

{ 'id': 'Microsoft', 'checked': false },

{ 'id': 'Apple', 'checked': false },

{ 'id': 'Micromax', 'checked': false }

];

this.os = [{ 'id': 'Android', 'checked': false },

{ 'id': 'Windows', 'checked': false },

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:
{ '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 }];

this.products = [];

this.productService.producttype = producttype;

this.productService.getProducts().subscribe({

next: products => {

this.products = products;

this.sortoption='';

},

error: error => this.errorMessage = error

});

// Invoked when user select an option in sort drop down

// changes the sortoption value accordingly

onChange(value: string) {

this.sortoption = value;

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558


Exp No: Page No:
Date:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0558

You might also like