Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 45

PRACTICAL-1

AIM: Setup Environment For Angular Framework By Installing Node.Js, Npm Package Manager
Using Editor Like Visual Code.
 Steps For Download NODE JS,NPM , CLI
Step 1: First Open Any Browser And Search Node Js, Then Simply Tap On NODE JS

Step 2: Tap On 18.15.0 LTS For Download NODE JS,

Step 3: Then Open That File And Tap On "INSTALL",

Step 4: After That Tick The Box And Tap On "INSTALL",


Step 5: Next Step Is Select The Path Where You Want To Place NODE JS,

Step 6: Tap On Next,

Step 7: Again Tap On Next,

Step 8: Tap On "INSTALL",


Wait For Complete The Process,

Step 9: Simply Tap On Finish,

Step 10: Now Open The Command Prompt And Check The Version On NODE JS And NPM

`
If The Versions Are Display There Then Installation Of NODE JS & NPM Is Completed.
Step 11: Now Install The CLI,

Wait For Complete The Process,


Here Installation & Setup Of NODE JS , NPM And CLI Is Completed.
Now Time To Install VS Code (Visual Studio Code)
Step12: Visit TheOfficial WebsiteOf The Visual Studio Code Using Any Web Browser Like Google Chrome,
Microsoft Edge, Etc.

Step 13: Press The “Download For Windows” Button On The Website To Start The Download Of The Visual Studio
Code Application.

Step 14: When The Download Finishes, Then The Visual Studio Code Icon Appears In The Downloads Folder.
Step 15: Click On The Installer Icon To Start The Installation Process Of The Visual Studio Code.
Step 16: After The Installer Opens, It Will Ask You For Accepting The Terms And Conditions Of The Visual Studio
Code. Click On I Accept The Agreement And Then Click The Next Button,

Step 17: Choose The Location Data For Running The Visual Studio Code. It Will Then Ask You For Browsing The
Location. Then Click On Next Button,
Step 18: Then It Will Ask For Beginning The Installing Setup. Click On The Install Button,

Step 19: After Clicking On Install, It Will Take About 1 Minute To Install The Visual Studio Code On Your Device,

Step 20: After The Installation Setup For Visual Studio Code Is Finished, It Will Show A Window Like This Below.
Tick The “Launch Visual Studio Code” Checkbox And Then Click On Finish,
Step 21:After The Previous Step, The Visual Studio Code Window Opens Successfully. Now You Can Create A New
File In The Visual Studio Code Window And Choose A Language Of Yours To Begin Your Programming Journey,
PRACTICAL-2
AIM :Create First Application To Print Hello World Message Using Angular Framework.

Step 1:First Open The Command Prompt, And Write "NG NEW APPLIVATION_NAME".

Step 2: Type "Y" And Give "ENTER".

Step 3: Again Give "ENTER".

Step 4:Wait Until Process Isn't complete.

Step 5:After The Completion The Process, Type "CD APPLICATION_NAME" (CD=Change Directory).
Step 6:After That Type "CODE ." It Open The VS CODE.

Step 7:Now Write Your Code In SRC APP APP.COMPONENT.HTML

<h1>HELLO WORLD</h1>

Step 8: now changes in SRC APP APP.COMPONENT.TS

In title tag
Enter your title

And Run That Code Using "F5" , In Last The Output Is,
PRACTICAL - 3
AIM :Design A Web Page To Utilize Property Binding And Event Binding Concepts Using Button And
Textbox Controls.

 Property Binding
First Go In SRC APP APP.COMPONENT.TS And Write
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
export class AppComponent{
userName:string="GTU";
}

After that go in In SRC APP APP.COMPONENT.HTML and write <input type="text" [value]="userName">
Output:

 Event Binding

First Go In SRC APP APP.COMPONENT.TS And Write

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


@Component({
selector: 'app-root',
templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
export class AppComponent {
showData($event:any) {
console.log("Button is Clicked!");
if($event) {
console.log($event.target);
console.log($event.target.value);
}} }

After That Go In SRC APP APP.COMPONENT.HTML And Write

<h2>event binding </h2><button (click)="showData($event)"> click here </button>

Output:
PRACTICAL - 4
AIM: Create various components of web page using Attribute Directives.

 First Go In SRC APP APP.COMPONENT.TS and Write:

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


@Component({
selector: 'my-app',
templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})export class AppComponent{ name = 'Angular ' + VERSION.full;
}
After that go in In SRC APP APP.COMPONENT.HTML and write
<h2 class="title" >Hello {{name}}</h2>
<div myDirective>
<!--dynamically add component through directive -->
<span>Hello</span></div>

Next go in SRC APP APP.MY.DIRECTIVE.TS and Write:


import { Directive, ElementRef, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from
'@angular/core';
import { DynamicComponent } from './dynamic/dynamic.component';
@Directive({ selector: '[myDirective]'
})
export class MyDirective {
constructor(private element: ElementRef, private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
){}
ngOnInit() {
constcomponentFactory = this.componentFactoryResolver
.resolveComponentFactory(DynamicComponent);
constcomponentRef = this.viewContainerRef.createComponent(componentFactory);
const host = this.element.nativeElement;
host.insertBefore(componentRef.location.nativeElement, host.firstChild)
}
}

Output :
PRACTICAL - 5
AIM :Design A Web Page To Display Student Grading System In Tabular Format With Alternate
Color Style Using Ngswitch, Ngstyle Directives.
First Go In SRC APP APP.COMPONENT.TS and Write:
import { Component } from '@angular/core';
@Component({
selector: 'app-practical-five',
templateUrl: './practical-five.component.html', styleUrls: ['./practical-five.component.scss']
})
export class PracticalFiveComponent{ studentGrades :any = [
{name: 'John', grade: 'A'},
{name: 'Jane', grade: 'B'},
{name: 'Mark', grade: 'C'},
{name: 'Mary', grade: 'D'}, {name: 'Peter', grade: 'F'}
];
}
After that go in In SRC APP APP.COMPONENT.HTML and write
<table>
<thead>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of studentGrades; index as even" [ngClass]="even % 2 === 0 ? 'bg-blue' : 'bgwhite'">
<td>{{ student.name }}</td>
<td [ngSwitch]="student.grade">
<span *ngSwitchCase="'A'" [ngStyle]="{'color': 'yellow'}">{{ student.grade }}</span>
<span *ngSwitchDefault>{{ student.grade }}</span>
</td>
</tr>
</tbody>
</table>
After that go in In SRC APP APP.COMPONENT.CSS and write table {
border-collapse: collapse; width: 100%; margin: 0%;
}

th, td {
text-align: center; padding: 18px; border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) { background-color: #f2f2f2;
}
tr:hover { background-color: #ddd;
} .bg-blue{ background-color: blue; color: white; }
.bg-white{ background-color: white; color: rgb(113, 41, 41);
}

Output:
PRACTICAL-6
AIM: Design component to perform following tasks
To Add or Remove number of students using textbox and button controls and display it in tabular
structure format.
Give row level remove button option to student table and record should be deleted when click on it.
Practical-six.component.ts:

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


@Component({
selector: 'app-practical-six', templateUrl: './practical-six.component.html', styleUrls: ['./practical-
six.component.scss']
}) export class PracticalSixComponent implements OnInit{ studentList: any = [
{ firstname: 'Rohan', roll_no: '12', address: 'add 1' },
{ firstname: 'Sohan', roll_no: '13', address: 'home town' },
{ firstname: 'Pooja', roll_no: '14', address: 'address 2' },
{ firstname: 'Aditi', roll_no: '15', address: 'panjab house' },
{ firstname: 'Rehan', roll_no: '16', address: 'sss' },
{ firstname: 'Ajay', roll_no: '17', address: 'asdsad' },
{ firstname: 'asdfg', roll_no: '176', address: 'asdsad' },
]
constructor() { } ngOnInit(): void {
}
addStudent() {
}
remove(index: any) { this.studentList.splice(index, 1)
}
}

Practical-six.component.html:
<div class="container">
<div class="row mt-4">
<div class="col-md-12 text-end">
<!--<button class="btnbtn-primary" (click)="addStudent()">
Add Student
</button> -->
</div>
</div>

<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Student Name</th>
<th scope="col">Roll Number</th>
<th scope="col">Address</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of studentList; index as k">
<th scope="row">{{k+1}}</th>
<td>{{item.firstname}}</td>
<td>{{item.roll_no}}</td>
<td>{{item.address}}</td>
<td><a class="pointer" (click)="remove(k)"><img height="20" width="20" src="https://cdn-icons-
png.flaticon.com/512/6861/6861362.png" alt=""></a>
</td>
</tr>
</tbody>
</table>
</div>

Output:
PRACTICAL-7
AIM: Create a component to display a products list from array. The product component should
display a product Id, name, purchase date, price, and image for the product and search using various
pipes.ts: . practical-7.component

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


@Component({
selector: 'app-practical-seven', templateUrl: './practical-seven.component.html', styleUrls: ['./practical-seven.component.scss']
}) export class PracticalSevenComponent implements OnInit{ searchText: any = ""; productList: any = [
{ id: this.rendomNumber(), name: "Oneplusnordce 2 lite", purchase_date: "2023-3-6", price: "19999", image:
"https://m.mediaamazon.com/images/I/413u56t+CiL._SY300_SX300_.jpg" },
{ id: this.rendomNumber(), name: "Samsung Galaxy A20", purchase_date: "2022-3-20", price: "20000", image:
"https://fdn2.gsmarena.com/vv/pics/samsung/samsung-galaxya20.jpg" },
{ id: this.rendomNumber(), name: "Iphone 13 pro", purchase_date: "2023-5-22", price:
"65000", image:
"https://img6.gadgetsnow.com/gd/images/products/additional/large/G215160_View_1/mobil es/smartphones/apple-iphone-13-pro-
256-gb-graphite-6-gb-ram-.jpg" },
{ id: this.rendomNumber(), name: "Redmi note 10", purchase_date: "2023-2-1", price:
"13000", image: "https://vlebazaar.in/image/cache/catalog/71IqJQM2stL._SL1500_-
550x550.jpg" },
{ id: this.rendomNumber(), name: "Samsung Galaxy A40", purchase_date: "2023-3-5", price: "35000", image:
"https://i.gadgets360cdn.com/products/large/1553058133_635_samsung_galaxy_a40.jpg?do wnsize=*:180" },
{ id: this.rendomNumber(), name: "Iphone 13 mini", purchase_date: "2023-3-16", price:
"700000", image:
"https://img1.gadgetsnow.com/gd/images/products/additional/large/G306186_View_1/mobil es/smartphones/apple-iphone-13-
mini-128-gb-starlight-4-gb-ram-.jpg" },
{ id: this.rendomNumber(), name: "Oneplus 11r", purchase_date: "2023-6-23", price:
"38999", image: "https://m.mediaamazon.com/images/I/41etLpNZV6L._SX300_SY300_QL70_FMwebp_.jpg" },
{ id: this.rendomNumber(), name: "Redmi note 10 pro max", purchase_date: "2023-1-2", price: "17000", image:
"https://img6.gadgetsnow.com/gd/images/products/additional/large/G226329_View_1/mobil es/smartphones/xiaomi-redmi-note-
10-pro-max-128-gb-vintage-bronze-8-gb-ram-.jpg" }, { id: this.rendomNumber(), name: "Realmenarzo 50A", purchase_date:
"2023-3-6", price:
"13000", image: "https://m.media-amazon.com/images/I/81Ke5qtC6oL._SX679_.jpg" }, { id: this.rendomNumber(), name:
"Oppo f15", purchase_date: "2023-4-17", price: "18500", image: "https://www.91-img.com/pictures/137067-v4-oppo-f15-mobile-
phonelarge-1.jpg?tr=q-80" },
{ id: this.rendomNumber(), name: "Iphone 13", purchase_date: "2023-4-8", price: "60000", image:
"https://cdn.shopify.com/s/files/1/0568/5942/7015/products/MLPH3HN_A_1.png?v=163237 1107" },
{ id: this.rendomNumber(), name: "Oneplus 2T", purchase_date: "2023-3-6", price:
"28500", image: "https://d2d22nphq0yz8t.cloudfront.net/88e6cc4b-eaa1-4053-af65563d88ba8b26/https://media.croma.com/
image/upload/v1664424925/Croma%20Assets/Com munication/Mobiles/Images/256970_0_gwomib.png/mxw_2048,f_auto" },
{ id: this.rendomNumber(), name: "Samsung Galaxy A30", purchase_date: "2023-3-6", price: "15500", image:
"https://i.gadgets360cdn.com/products/large/1551094093_635_samsung_galaxy_a_30.jpg?do wnsize=*:180" },
{ id: this.rendomNumber(), name: "Redmi note 10 pro", purchase_date: "2023-1-1", price:
"15000", image: "https://m.media-amazon.com/images/I/418oiD-
2kLL._SX300_SY300_QL70_FMwebp_.jpg" },
{ id: this.rendomNumber(), name: "vivo v20", purchase_date: "2023-5-21", price: "21500", image:
"https://www.addmecart.com/wp-content/uploads/2022/11/22-2.jpg" },
]

constructor() { } ngOnInit(): void {


}
rendomNumber() { return Math.floor(Math.random() * 1000000)
}
}

practical-7.component.html:
<div class="container">
<div class="row my-4">
<div class="col-md-6">
<input type="text" class="form-control" placeholder="search here..."
[(ngModel)]="searchText" name="searchText">
</div>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">name</th>
<th scope="col">purchase date</th>
<th scope="col">price</th>
<th scope="col">image</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of productList | filter:searchText">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.purchase_date| date:'mediumDate'}}</td>
<td>{{item.price}}</td>
<td><img [src]="item.image" width="100" height="100"></td>
</tr>
</tbody>
</table>
</div>
OUTPUT:
PRACTICAL-8
AIM: Design a student registration page using template driven form approach and utilize different
form and controls level ng validation classes. practical-8.component.ts:

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


@Component({
selector: 'app-practical-eight', templateUrl: './practical-eight.component.html', styleUrls: ['./practical-
eight.component.scss']
}) export class PracticalEightComponent implements OnInit{ formObj: any = {} isDisable: boolean = false;
constructor() { } ngOnInit(): void {
}
submit(form: any) { console.log("form??", form); console.log("form??", form.valid);
}
}

practical-8.component.html:
<div class="container mt-5">
<form #quickAdd="ngForm">
<div class="row">
<div class="col-md-6 mb-3">
<div class="row">
<label class="col-sm-4 col-form-label">Student Name<sup>*</sup></label>
<div class="col-sm-8">
<input type="text" class="form-control" [(ngModel)]="formObj.studentname" name="studentName"
#studentname="ngModel" required placeholder="Student Name">
<div class="text-danger" *ngIf="studentname.errors&&quickAdd.submitted">
<div *ngIf="studentname.errors.required">Student Name is required</div>
</div>
</div>
</div>
</div>

<div class="col-md-6 mb-3">


<div class="row">
<label class="col-sm-4 col-form-label">Father Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" [(ngModel)]="formObj.fathername" name="fathername"
#fathername="ngModel" placeholder="Father Name">
<!--<div class="text-danger" *ngIf="fathername.errors&&quickAdd.submitted">
<div *ngIf="fathername.errors.required">Father Name is required</div>
</div> -->
</div>
</div>
</div>

<div class="col-md-6 mb-3">


<div class="row">
<label class="col-sm-4 col-form-label">Mother Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" [(ngModel)]="formObj.mothername" name="mothername"
#motherName="ngModel" placeholder="Mother Name">
<!--<div class="text-danger" *ngIf="motherName.errors&&quickAdd.submitted">
<div *ngIf="motherName.errors.required">Mother Name is required</div>
</div> -->
</div></div>
</div>
<div class="col-md-6 mb-3">
<div class="row">
<label class="col-sm-4 col-form-label">Roll Number</label>
<div class="col-sm-8">
<input type="text" class="form-control" [(ngModel)]="formObj.rollno" numbersOnly name="rollno"
placeholder="Roll Number">
</div>
</div>
</div>

<div class="col-md-6 mb-3">


<div class="row">
<label class="col-sm-4 col-form-label">Date of birth<sup>*</sup></label>
<div class="col-sm-8">
<input type="date" class="form-control" [(ngModel)]="formObj.birthdate" name="birthdate" required
#DOB="ngModel">
<div class="text-danger" *ngIf="DOB.errors&&quickAdd.submitted">
<div *ngIf="DOB.errors.required">Date of birth is required</div>
</div>
</div>
</div>
</div>

<div class="col-md-6 mb-3">


<div class="row">
<label class="col-sm-4 col-form-label">Phone No.<sup>*</sup></label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Phone No."
[(ngModel)]="formObj.c_phone" required name="c_phone" #c_phone="ngModel" required minlength="10"
maxlength="10">
<div class="text-danger" *ngIf="c_phone.errors&&quickAdd.submitted">
<div *ngIf="c_phone.errors?.required">Phone No is required</div>
<div *ngIf="c_phone.errors?.minlength">Enter 10 digit Mobile Number</div>
</div>
</div>
</div>
</div>

<div class="col-md-6 mb-3">


<div class="row">
<label class="col-sm-4 col-form-label">House<sup>*</sup></label>
<div class="col-sm-8">
<input type="text" class="form-control" [(ngModel)]="formObj.house" name="house" required #house="ngModel"
placeholder="House">
<div class="text-danger" *ngIf="house.errors&&quickAdd.submitted">
<div *ngIf="house.errors.required">House is required</div>
</div>
</div>
</div>
</div>
<div class="col-md-6 mb-3">
<div class="row">
<label class="col-sm-4 col-form-label">Gender</label>
<div class="col-sm-8">
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="r1">
<label class="form-check-label" for="r1"> Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="r2">
<label class="form-check-label" for="r2"> Female
</label>
</div>
</div>
</div>
</div>
<div class="col-md-12 mb-3 text-center">
<button type="submit" class="btnbtn-primary" (click)="submit(quickAdd.form)">
Submit
</button>
</div>
</div>
</form></div>

OUTPUT:
PRACTICAL-9
AIM: Design component to enter faculty details like Code, Name, Email, Type, Faculty Status (Active,
Inactive), Subjects Teaching (with option to add multiple subjects dynamically) using reactive form
with various types of validation of form and controls. Practical-9.component.ts:

import { Component, OnInit } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators }
from '@angular/forms';
@Component({
selector: 'app-prectical-nine', templateUrl: './prectical-nine.component.html', styleUrls: ['./prectical-
nine.component.scss']
}) export class PrecticalNineComponent implements OnInit{ facultyForm: any = this.fb.group({ code: ['',
[Validators.required]], name: ['', [Validators.required]], email: ['', [Validators.required]], type: ['',
[Validators.required]], status: ['', [Validators.required]], subjects: this.fb.array([]),
});
submitted = false; constructor(private fb: FormBuilder) { this.facultyForm.subject = this.fb.group({ subjects:
this.fb.array([])
});
} ngOnInit() {

addSubject() { const subject = this.fb.group({ name: ['', Validators.required], code: ['', Validators.required]
});
console.log("subject>", subject) this.subjects.push(subject);
}
get subjects() { return this.facultyForm.get('subjects') as FormArray;
}
removeData(index: number) { this.subjects.removeAt(index);
}

get f() { return this.facultyForm.controls; }

onSubmit() { this.submitted = true;

// stop here if form is invalid if (this.facultyForm.invalid) { return;


}
// display form values on success console.log(">>>>", this.facultyForm.values)
}

onReset() { this.submitted = false; this.facultyForm.reset();


}
}

Practical-9.component.html:
<div class="card m-3">
<h5 class="card-header">Angular 10 Reactive Form Validation</h5>
<div class="card-body">
<form [formGroup]="facultyForm" (ngSubmit)="onSubmit()">
<div class="form-row">

<div class="form-group col-7 mt-3">


<label>Code</label>
<input type="text" formControlName="code" class="form-control"
[ngClass]="{ 'is-invalid': submitted &&f.code.errors }" />
<div *ngIf="submitted &&f.code.errors" class="invalid-feedback">
<div *ngIf="f.code.errors.required">Code is required</div>
</div>
</div>

<div class="form-group col-7 mt-3">


<label>Name</label>
<input type="text" formControlName="name" class="form-control"
[ngClass]="{ 'is-invalid': submitted &&f.name.errors }" />
<div *ngIf="submitted &&f.name.errors" class="invalid-feedback">
<div *ngIf="f.name.errors.required">Name is required</div>
</div>
</div>

<div class="form-group col-7 mt-3">


<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted
&&f.email.errors }" />
<div *ngIf="submitted &&f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
</div>
</div>

<div class="form-group col-7 mt-3">


<label>Type</label>
<input type="text" formControlName="type" class="form-control"
[ngClass]="{ 'is-invalid': submitted &&f.type.errors }" />
<div *ngIf="submitted &&f.type.errors" class="invalid-feedback">
<div *ngIf="f.type.errors.required">Type is required</div>
</div>
</div>

<div formArrayName="subjects">
<div *ngFor="let subject of subjects.controls; index as i" class="form-group">
<div [formGroupName]="i">
<label>Name</label>
<input type="text" formControlName="name" class="form-control">
<label>age</label>
<input type="text" formControlName="age" class="form-control">
<button type="button" (click)="removeData(i)">Remove</button>
</div>
</div>
<button type="button" (click)="addSubject()">Add Data</button></div>

<div class="form-group col-7 mt-3">


<label>Faculty Status</label>
<select formControlName="status" class="form-control"
[ngClass]="{ 'is-invalid': submitted &&f.status.errors }">
<option value="">--select--</option>
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
</select>
<div *ngIf="submitted &&f.status.errors" class="invalid-feedback">
<div *ngIf="f.status.errors.required">Faculty Status is required</div>
</div>
</div>
</div>
<div class="text-center mt-4">
<button class="btnbtn-primary mr-1">Register</button>
<button class="btnbtn-secondary" type="reset" (click)="onReset()">Cancel</button>
</div>
</form>
</div>
</div>

OUTPUT:
PRACTICAL-10
AIM: Design a page to implement Add to Cart functionality using decorators, custom properties,
custom events of component communication.

First create application with name shopping:


ng new shopping
Then move to shopping directory:
cd shopping
Now create three components:
ng g c product-list ng g c shopping-cart ng g c cart-product
____________________________________________ app.component.html
<app-product-list [products]="productList"
(productAdded)="addProductToCart($event)"></app-product-list>
<app-shopping-cart [products]="cartProductList"
(productRemoved)="removeProduct($event)"></app-shopping-cart>
___________________________________________ app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less']
})
export class AppComponent {
title = 'shopping';
productList = [
{name: 'Bike Cover', price: 799},
{name: 'Helmet', price: 999},
{name: 'Sport Gloves', price: 99}
];
cartProductList = Array(); addProductToCart(product:any) { constproductExistInCart = this.cartProductList
.find(({name}) => name === product.name); // find product by name
if (!productExistInCart) { this.cartProductList.push({...product, num:1}); // enhance "porduct" opject with
"num" property
return;
}
productExistInCart.num += 1;
}
removeProduct(product:any) { this.cartProductList = this.cartProductList.filter(({name}) => name !==
product.name) } }
________________________________________________________ app.component.css
:host { display: grid;
grid-template-columns: 1fr 1fr; grid-column-gap: 10px;
}
_____________________________________________________

app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import
{ AppComponent } from './app.component'; import { ProductListComponent } from './product-list/product-
list.component'; import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component'; import
{FormsModule} from '@angular/forms'; import { CartProductComponent } from './cart-product/cart-
product.component'
@NgModule({
declarations: [
AppComponent,
ProductListComponent,
ShoppingCartComponent,
CartProductComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
__________________________________________ product-list.component.tsimport { Component,
Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.less']
})
export class ProductListComponent {
@Input() products: any[]= Array();
@Output() productAdded = new EventEmitter(); addProductToCart(product:any)
{ this.productAdded.emit(product);
}
}
_____________________________________________ product-list.component.html
<h1>Products List</h1>
<div *ngFor="let product of products">{{product.name}} ---- <button
(click)="addProductToCart(product)">+</button>
<div>{{product.price|currency}}</div></div> ________________________________________________ product-
list.component.css
:host{border: 1px solid #000;}
_______________________________________________ shopping-cart.component.ts
import { Component ,Input,Output,EventEmitter} from '@angular/core';
@Component({
selector: 'app-shopping-cart', templateUrl: './shopping-cart.component.html', styleUrls: ['./shopping-
cart.component.less']
})
export class ShoppingCartComponent {
@Input() products: any[]=Array();
@Output() productRemoved = new EventEmitter();
calcTotal() { return this.products.reduce((acc, prod) =>acc+= prod.num ,0)
}
removeProduct(product:any) { this.productRemoved.emit(product)
}
}
______________________________________________ shopping-cart.component.html
<h1>Shopping Cart ({{calcTotal()}})</h1>
<app-cart-product *ngFor="let product of products"
[product]="product" (productRemoved)="removeProduct($event)"><app-cart-product>
_____________________________________________ shopping-cart.component.css
:host{border: 1px solid #000;}
_____________________________________________ cart-product.component.ts
import { Component,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-cart-product', templateUrl: './cart-product.component.html', styleUrls: ['./cart-
product.component.less']
})
export class CartProductComponent {
@Input() product: any;
@Output() productRemoved = new EventEmitter(); modelChanged(product:any) {
if (this.product.num === 0) { this.productRemoved.emit(this.product)
}
}
}
___________________________________________________ cart-product.component.html
<div *ngIf="product">
<div>{{product.name}}</div>
<input type="number" [(ngModel)]="product.num" min="0"
(ngModelChange)="modelChanged($event)"/>
</div>

OUTPUT:
PRACTICAL-11
AIM: Develop page to demonstrate different methods of angular component lifecycle.

Create new project: ng new LifeCycleHooks


app.component.html
<div class="main-content">
<h1>Hello World...</h1>
<form (submit)="addStudent()">
<input type="text" [(ngModel)]="studentName" name="studentName" id="studentName">
<button>Add Student</button>
</form>
<app-student-list [studentList]="students">
<div #titleContent>This is Student List</div>
</app-student-list>
</div>
____________________________________ app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'],
})
export class AppComponent {
studentName = ''; students = ['Mayur', 'Mira'];

ngOnInit() { console.log('ngOnInit from the parent component');


}
addStudent = () =>{ this.students.push(this.studentName); this.studentName = '';
};
}
__________________________________ app.component.css
.main-content { margin: 5rem auto; text-align: center;
} ul li { list-style: none;
}
___________________________________ 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 { StudentListComponent } from './student-list/student-
list.component';

@NgModule({
declarations: [
AppComponent,
StudentListComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
_______________________________________________ now create new componet using: ng g c student-list
____________________________ student-list.component.html
<!--<p>student-list works!</p> -->
<div #title>
<ng-content></ng-content>
</div>
<ul>
<li *ngFor="let student of students">{{student}}</li>
</ul>
______________________________________________ student-list.component.css
ul li { list-style: none;
}
___________________________________________________ student-list.component.ts
import {
Component,
ContentChild,
ElementRef,
Input,
SimpleChanges,
ViewChild,
} from '@angular/core';

@Component({
selector: 'app-student-list', templateUrl: './student-list.component.html', styleUrls: ['./student-list.component.scss'],
})
export class StudentListComponent {
@Input('studentList') students: string[] = [];
@ViewChild('title') wrapper!:ElementRef;
@ContentChild('titleContent') content!:ElementRef; ngOnChanges(changes: SimpleChanges)
{ console.log('ngOnChanges triggered', changes);
}
ngOnInit() { console.log('ngOnInit from the child component');
}
ngDoCheck() { console.log('ngDoCheck triggered');
}
ngAfterContentInit() { console.log('ngAfterContentInit - title', this.wrapper); console.log('ngAfterContentInit -
titleContent', this.content);
}
ngAfterContentChecked(): void { console.log('ngAfterContentChecked triggered');
}
ngAfterViewInit(): void { console.log('ngAfterViewInit - wrapper', this.wrapper);
}
ngAfterViewChecked(): void { console.log('ngAfterViewChecked triggered');
}
}
_______________________________
run the project using:
ng serve
add students data and see the life cycle change in the console log (right click and inspect element)

OUTPUT:
PRACTICAL-12
AIM: Design an e-commerce product page and product details page that displays product details
when clicking on any particular product.

First create application with name ecommerce:


ng new ecommerce
Then move to ecommerce directory:
cd ecommerce
Now create three components:
ng g c product-list ng g c product-details ng g c topbar
_____________________________________________
create interface to store product details:
ng g i product
_____________________________________________ product.ts
export interface Product { id: number; name: string; price: number; description: string;
}
export const products: Product[] = [
{ id: 1,
name: 'Phone XL',
price: 799, description: 'A large phone with one of the best screens'
}, { id: 2,
name: 'Phone Mini', price: 699,
description: 'A great phone with one of the best cameras'
}, { id: 3,
name: 'Phone Standard',
price: 299, description: ''
}
];
____________________________________________ app.component.html
<app-topbar></app-topbar>
<div>
<router-outlet></router-outlet>
</div>
___________________________________________ app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import
{ ProductDetailsComponent } from './product-details/product-details.component'; import { ProductListComponent }
from './product-list/product-list.component';
const routes: Routes = [ { path: '', component: ProductListComponent },
{ path: 'products/:productId', component: ProductDetailsComponent }];
@NgModule({
imports: [RouterModule.forRoot(routes)], exports: [RouterModule]
})
export class AppRoutingModule {
}
_____________________________________________________ app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import
{ FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import
{ AppComponent } from './app.component'; import { TopbarComponent } from './topbar/topbar.component'; import
{ ProductListComponent } from './product-list/product-list.component'; import { ProductDetailsComponent } from
'./product-details/product-details.component';
@NgModule({
declarations: [
AppComponent,
TopbarComponent,
ProductListComponent,
ProductDetailsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
__________________________________________ product-list.component.tsimport { Component } from
'@angular/core'; import { products } from '../products';

@Component({
selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.less']
})
export class ProductListComponent{ products = products;
}
____________________________________________

product-list.component.html
<h2>Products</h2>
<div *ngFor="let product of products">
<h3>
<a [routerLink]="['/products', product.id]">
{{ product.name }}
</a>
</h3>
<p *ngIf="product.description">
Description: {{ product.description }}
</p>
</div>
________________________________________________ product-details.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import
{ Product, products } from '../products';

@Component({
selector: 'app-product-details', templateUrl: './product-details.component.html', styleUrls: ['./product-
details.component.less']
})
export class ProductDetailsComponent implements OnInit{ product: Product|undefined;
constructor(
private route: ActivatedRoute,
){}

ngOnInit() {
// First get the product id from the current route. constrouteParams = this.route.snapshot.paramMap;
constproductIdFromRoute = Number(routeParams.get('productId'));

// Find the product that correspond with the id provided in route.


this.product = products.find(product => product.id === productIdFromRoute);
}
}
______________________________________________ product-details.component.html
<h2>Product Details</h2>
<div *ngIf="product">
<h3>{{ product.name }}</h3>
<h4>{{ product.price | currency }}</h4>
<p>{{ product.description }}</p>
</div>
_____________________________________________ topbar.component.html
<a [routerLink]="['/']">
<h1>My Store</h1></a>

OUTPUT:
PRACTICAL-13
AIM: Design a page to display student information using dependency Injection.

First create application with name injectionExample:


ng new injectionExample
Then move to injectionExample directory: cd injectionExample
-------------------------------------------------------------------------------------------------
create interface for student ng g i student student.ts:
export interface Student { studentFirstName: string; studentLastName: string; studentRegistrationNumber: string;
studentCourse: string; studentYearOfStudy: number; reportingDate: string; college: string;
}
-------------------------------------------------------------------------------------------------
Run the following command to create studentListService. ng g service student-list student-list.service.ts:
import { Injectable } from '@angular/core'; import {Student} from './student';

@Injectable({ providedIn: 'root'


}) export class StudentListService{ getInternsDetails(): Student[] {
return [
{
studentFirstName: 'ABC',
studentLastName: 'XYZ', studentRegistrationNumber: 'TRD12345STR', studentCourse: 'Computer Science',
studentYearOfStudy: 1, reportingDate: '2019-07-20', college: 'GTU',
},
{
studentFirstName: 'Alice', studentLastName: 'Liz',
studentRegistrationNumber: 'DRTRD12345STR', studentCourse: 'Software Engineering', studentYearOfStudy:
1, reportingDate: '2020-07-19', college: 'GTU',
},
{
studentFirstName: 'Jonty', studentLastName: 'Miro', studentRegistrationNumber: 'YR6353', studentCourse:
'Information technology', studentYearOfStudy: 1, reportingDate: '2019-07-20', college: 'Gujarat
University',
},
{
studentFirstName: 'Jakob', studentLastName: 'Jack', studentRegistrationNumber: 'YTT64749EJFHR',
studentCourse: 'Computer Engineering', studentYearOfStudy: 1, reportingDate: '2019-02-10',
college: 'Saurashtra University',
},
{
studentFirstName: 'Prince', studentLastName: 'Sawoo', studentRegistrationNumber: 'ETRHDDIE857EHD',
studentCourse: 'Computer Science', studentYearOfStudy: 1, reportingDate: '2019-03-30', college: 'GTU',
}
];
}}
-----------------------------------------------------------------------------------------------------------
Create a student component by executing the following commands: ng g c student student.component.ts:
import { Component, OnInit } from '@angular/core'; import {StudentListService} from '../student-list.service'; import
{Student} from '../student';

@Component({
selector: 'app-student', templateUrl: './student.component.html', styleUrls: ['./student.component.css']
})
export class StudentComponent implements OnInit {
students!: Student[];
constructor(private studentListService: StudentListService) { }
ngOnInit() {
this.getStudentsList();
}
getStudentsList() {
this.students = this.studentListService.getInternsDetails();
}
}
--------------------------------------------------------------------------------------------------------------
student.component.html:
<div>
<table class="table table-stripped table-active">
<thead class="thead-light">
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Admission Number</th>
<th>Course</th>
<th>Year Of Study</th>
<th>Reported On</th>
<th>College</th>
</thead>
<tbody>
<tr *ngFor="let student of students;leti=index">
<td>{{i+1}}</td>
<td>{{student.studentFirstName}}</td>
<td>{{student.studentLastName}}</td>
<td>{{student.studentRegistrationNumber}}</td>
<td>{{student.studentCourse}}</td>
<td>{{student.studentYearOfStudy}}</td>
<td>{{student.reportingDate}}</td>
<td>{{student.college}}</td>
</tr>
</tbody>
</table></div>
------------------------------------------------------------------------------------------------------------- app.component.html:
<app-student></app-student>
<div>
<router-outlet></router-outlet>
</div>

OUTPUT:
PRACTICAL-14
AIM: Develop a page for product listing and search-as-you-type using observables and web APIs from
database.

Step 1: Set up Angular Project ng new product-listing-app cd product-listing-app


Step 2: Create a Product Service
// product.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import
{ Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class ProductService{ private apiUrl = 'https://api.example.com/products'; constructor(private http:
HttpClient) {} getProducts(): Observable<any> { return this.http.get<any>(this.apiUrl);
}
searchProducts(query: string): Observable<any> { return this.http.get<any>(`${this.apiUrl}?q=${query}`);
}
}

Step 3: Create a Product Listing Component


// product-list.component.ts
import { Component, OnInit } from '@angular/core'; import { ProductService } from '../services/product.service';
import { Observable } from 'rxjs';

@Component({
selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit{ products$: Observable<any>;
searchQuery: string = ''; constructor(private productService: ProductService) {} ngOnInit() { this.fetchProducts();
}
fetchProducts() { this.products$ = this.productService.getProducts();
}
searchProducts() { this.products$ = this.productService.searchProducts(this.searchQuery);
}
}

<!-- product-list.component.html -->


<input type="text" [(ngModel)]="searchQuery" (input)="searchProducts()" placeholder="Search Products">
<ul>
<li *ngFor="let product of products$ | async">
{{ product.name }}
</li>
</ul>
Step 4: App Module Configuration
// app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import
{ HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import
{ AppComponent } from './app.component'; import {ProductListComponent } from
'./components/product-list/product-list.component'; import { ProductService } from './services/product.service';
@NgModule({
declarations: [
AppComponent,
ProductListComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [ProductService], bootstrap: [AppComponent]
})
export class AppModule{ }Step 5: Run the Application ng serve
Please note that this is a basic example, and you may need to adjust the code according to your specific database and
API requirements.
PRACTICAL-15
AIM: Design web page to display student data in table using HTTP GET/POST Calls from web APIs.

Step-1 Set up your Angular project:


Create a new Angular project using the command ng new student-table-app
Navigate into the project directory using cd student-table-app
Step-2 Create a service to handle HTTP requests:
Generate a new service using the command ng generate service student
Open the generated student.service.ts file and import the necessary modules:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
Inject the HttpClient in the constructor:
constructor(private http: HttpClient) { }
Define methods to handle GET and POST requests:
getStudents() { return this.http.get('/api/students');
} addStudent(student: any) {
return this.http.post('/api/students', student);
}
Step-3 Create a component to display the student table:
Generate a new component using the command ng generate component studenttable
Open the generated student-table.component.ts file and import the necessary modules:
import { Component, OnInit } from '@angular/core'; import { StudentService } from '../student.service';

Inject the StudentService in the constructor:


constructor(private studentService: StudentService) { }
Define an array to store the student data:
students: any[] = [];
Implement the ngOnInit() method to fetch the student data: ngOnInit()
{ this.studentService.getStudents().subscribe((data: any) => { this.students = data;
});
}
Step-4 Create the HTML template for the component:
Open the generated student-table.component.htmlfile and add the following code:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of students">
<td>{{ student.id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
</tr>
</tbody>
</table>
Step-5 Update the app component:
Open the app.component.html file and replace its content with the following code:
<app-student-table></app-student-table>
<div><router-outlet></router-outlet></div>

Step-6 Update the app module:


Open the app.module.ts file and import the necessary modules: import { HttpClientModule } from
'@angular/common/http';
Add HttpClientModule to the imports array:
imports: [
HttpClientModule
]
Step-7 Run the application:
Start the development server using the command ng serve
Make sure to replace the API endpoints (/api/students) in the student.service.ts file with the actual endpoints of web
API. Also, customize the table headers and student object properties
PRACTICAL-16
AIM:Design web page to insert product data in table using web APIs.

Step-1 Set up your Angular project:


Create a new Angular project using the command ng new product-table-app
Navigate into the project directory using cd product-table-app
Step-2 Create a service to handle HTTP requests:
Generate a new service using the command ng generate service product
Open the generated product.service.ts file and import the necessary modules:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
Inject the HttpClient in the constructor: constructor(private http: HttpClient) { }
Define a method to handle POST requests: addProduct(product: any) {
return this.http.post('/api/products', product);
}
Step-3 Create a component to display the product table and insert form:
Generate a new component using the command ng generate component producttable
Open the generated product-table.component.ts file and import the necessary modules:
import { Component, OnInit } from '@angular/core'; import { ProductService } from '../product.service';
import { NgForm } from '@angular/forms';
Inject the ProductService in the constructor:
constructor(private productService: ProductService) { }

Implement the ngOnInit() method to initialize any necessary data. Define a method to handle form submission:
onSubmit(form: NgForm) {
if (form.valid) { const product = form.value; this.productService.addProduct(product).subscribe(() => {
// Reset the form after successful submission form.reset();
// Optional: Fetch the updated product list to reflect the changes in the table this.getProducts();
});
}
}
Step-4 Create the HTML template for the component:
Open the generated product-table.component.html file and add the following code:
<h2>Add Product</h2>
<form (ngSubmit)="onSubmit(productForm)" #productForm="ngForm"><div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" [(ngModel)]="product.name" required></div>
<div>
<label for="price">Price:</label>
<input type="number" id="price" name="price" [(ngModel)]="product.price" required>
</div>
<button type="submit" [disabled]="!productForm.valid">Add</button></form>

<h2>Product List</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of products">
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
</tr>
</tbody>
</table>
Step-5 Update the app component:
Open the app.component.htmlfile and replace its content with the following code:
<app-product-table></app-product-table>
<div>
<router-outlet></router-outlet>
</div>
Step-6 Update the app module:
Open the app.module.ts file and import the necessary modules: import { HttpClientModule } from
'@angular/common/http';
import { FormsModule } from '@angular/forms';
Add HttpClientModule and FormsModule to the imports array:
imports: [
HttpClientModule,
FormsModule
]
Step-7 Run the application:
Start the development server using the command ng serve

Remember to replace the API endpoint (/api/products) in the product.service.ts file with the actual endpoint of web
API. Additionally, you can customize the form fields and the table headers based on your specific requirements.
PRACTICAL-17
AIM: Design a page to implement Multiview component with login, logout functionalities using
different routing options. practical-sevnteen.component.ts:

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

@Component({ selector:'app-practical-sevnteen',
templateUrl:'./practical-sevnteen.component.html',
styleUrls: ['./practical-sevnteen.component.scss']
}) exportclasspracticalSevnteenComponentimplementsOnInit{
isLoggedIn:boolean=false; username:string='';
password:string=''; constructor() { }
ngOnInit():void {
}
login():void {
// Perform login logic here, e.g., call an authentication serviceif
(this.username==='admin'&&this.password==='password') {
this.isLoggedIn=true;
} }
logout():void {
// Perform logout logic here, e.g., clear session or
tokenthis.isLoggedIn=false;
}
}

practical-sevnteen.component.html:
<divclass="container"><div*ngIf="isLoggedIn;
elseloginView">
<h1>Welcome, User!</h1>
<buttonclass="btnbtn-dange mt-3r"
(click)="logout()">Logout</button>
</div>

<ng-template#loginView>
<!-- Login view -->
<h1>Login</h1>
<divclass="row">
<form(submit)="login()">
<divclass="col-md-6 mb-3">
<inputtype="text"[(ngModel)]="username"name="uu"placeholder="Username"required
class="form-control">
</div>

<divclass="col-md-6 mb-3">
<inputtype="password"class="form-control"
[(ngModel)]="password"name="ii"placeholder="Password"required>
</div>

<divclass="col-md-12">
<buttonclass="btnbtn-primary"type="submit">Login</button>
</div>
</form>
</div>
</ng-template>
</div>
OUTPUT:
PRACTICAL-18
AIM: Develop a page to demonstrate page navigation of product list using routing concepts.
Practical-eighteen.component.ts:

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


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

@Component({
selector: 'app-practical-eighteen',
templateUrl: './practical-eighteen.component.html',
styleUrls:['./practical-eighteen.component.scss']
})
export class PracticalEighteenComponent implements OnInit {
constructor(public pt: ProductService) {}
ngOnInit(): void {
}
Practical-eighteen.component.html:

<div class="container text-center mt-5">


<div class="row">
<div class="col-md-12 mb-3" *ngFor="let product of pt.products">
<a [routerlink]="['/practical-eighteen',product.id]">{{
product.name }}</a>
</div>
</div>
</div>
practical-eighteen-details.component.html:
import{ Component, OnInit } from'@angular/core'; import {
ActivatedRoute } from'@angular/router'; import {
ProductService } from'../product.service';

@Component({ selector:'app-practical-eighteen-details',
templateUrl:'./practical-eighteen-details.component.html',
styleUrls: ['./practical-eighteen-details.component.scss']
}) exportclassPracticalEighteenDetailsComponentimplementsOnInit {
productId:any;
product:any;
constructor( privateroute:ActivatedRoute,
privateproductService:ProductService
) { }ngOnInit() { this.route.paramMap.subscribe((params:any) => {
this.productId=+params.get('id');
this.product=this.productService.getProduct(this.productId);
});
}
<divclass="container text-center mt-5">
<h2>{{product.name}}</h2>
<p>{{product.description}}</p>
</div>

OUTPUT:
PRACTICAL-19
AIM: Design a page to load customer and Sales order data using lazy loading technique in angular.
Customer list:
practical-nineteen-one.component.ts:

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


@Component({ selector:'app-practical-nineteen-one',
templateUrl:'./practical-nineteen-one.component.html',
styleUrls: ['./practical-nineteen-one.component.scss']
}) exportclassPracticalNineteenOneComponentimplementsOnInit {
constructor() { }
ngOnInit():void {
}
}
practical-nineteen-one.component.html
<p>practical-nineteen-one works!</p>

Sales order:
practical-nineteen-two/practical-nineteen-two.component.ts:
import{ NgModule } from'@angular/core'; import { RouterModule, Routes }
from'@angular/router'; import { PracticalNineteenTwoComponent }
from'./practical-nineteentwo/practical-nineteen-two.component';
constroutes:Routes= [
{ path:'', component:PracticalNineteenTwoComponent }
];
@NgModule({ imports:
[RouterModule.forChild(routes)], exports:
[RouterModule]
})
exportclassSelesorderRoutingModule{ }

OUTPUT:
PRACTICAL-20
AIM: Design a page to implement CORS concept. practical-twenty.component.ts:
practical-twenty.component.html

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


HttpClient } from'@angular/common/http';
@Component({ selector:'app-practical-twenty',
templateUrl:'./practical-twenty.component.html',
styleUrls: ['./practical-twenty.component.scss']
}) exportclassPracticalTwentyComponentimplementsOnInit{
constructor(privatehttp:HttpClient) { }
ngOnInit():void {
this.makeCorsRequest();
} makeCorsRequest():void {
consturl='https://api.example.com/data';
this.http.get(url, { responseType:'text' })
.subscribe( response=> {
console.log('Response:', response);
}, error=> {
console.log('Error:', error);
}
);
}
}
<h1>CORS Example</h1>

OUTPUT:

You might also like