MPT Lab Manual Solution
MPT Lab Manual Solution
AIM :
Setup Environment For Angular Framework By Installing Node.Js, Npm Package Manager
Using Editor Like Visual Code.
Step 5: Next Step Is Select The Path Where You Want To Place NODE JS,
Step 6: Tap On Next,
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,
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 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".
<h1>HELLO WORLD</h1>
AIM : Design A Web Page To Utilize Property Binding And Event Binding Concepts Using
Button And Textbox Controls.
Property Binding
Output:
Event Binding
ngOnInit() {
const componentFactory = this.componentFactoryResolver
.resolveComponentFactory(DynamicComponent);
Output:
Practical - 5
AIM : Design A Web Page To Display Student Grading System In Tabular Format
With Alternate Color Style Using Ngswitch, Ngstyle Directives.
@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'}
];
}
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
A) To Add or Remove number of students using textbox and button
controls and display it in tabular structure format.
B) Give row level remove button option to student table and record should
be deleted when click on it.
Practical-six.component.ts:
<div class="container">
<div class="row mt-4">
<div class="col-md-12 text-end">
<!-- <button class="btn btn-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:
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:
practical-8.component.html:
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:
}
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);
}
onSubmit() {
this.submitted = true;
Practical-9.component.html:
<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>
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
cd shopping
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']
})
title = 'shopping';
productList = [
];
cartProductList = Array();
addProductToCart(product:any) {
if (!productExistInCart) {
this.cartProductList.push({...product, num:1});
return;
productExistInCart.num += 1;
removeProduct(product:any) {
________________________________________________________
app.component.css
:host {
display: grid;
grid-template-columns: 1fr 1fr;
grid-column-gap: 10px;
}
_____________________________________________________
app.module.ts
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent,
ProductListComponent,
ShoppingCartComponent,
CartProductComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
__________________________________________
product-list.component.ts
import { Component, Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.less']
})
addProductToCart(product:any) {
this.productAdded.emit(product);
_____________________________________________
product-list.component.html
<h1>Products List</h1>
<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']
})
calcTotal() {
removeProduct(product:any) {
this.productRemoved.emit(product)
______________________________________________
shopping-cart.component.html
<h1>Shopping Cart ({{calcTotal()}})</h1>
[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 {
modelChanged(product:any) {
if (this.product.num === 0) {
this.productRemoved.emit(this.product)
___________________________________________________
cart-product.component.html
<div *ngIf="product">
<div>{{product.name}}</div>
</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()">
<button>Add Student</button>
</form>
<app-student-list [studentList]="students">
</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 = '';
ngOnInit() {
addStudent = () => {
this.students.push(this.studentName);
this.studentName = '';
};
__________________________________
app.component.css
.main-content {
text-align: center;
ul li {
list-style: none;
___________________________________
app.module.ts
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent,
StudentListComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
_______________________________________________
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'],
})
ngOnInit() {
ngDoCheck() {
console.log('ngDoCheck triggered');
ngAfterContentInit() {
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked triggered');
ngAfterViewInit(): void {
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
cd ecommerce
ng g c product-list
ng g c product-details
ng g c topbar
_____________________________________________
ng g i product
_____________________________________________
product.ts
export interface Product {
id: number;
name: string;
price: number;
description: string;
id: 1,
},
id: 2,
price: 699,
},
id: 3,
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';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
_____________________________________________________
app.module.ts
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent,
TopbarComponent,
ProductListComponent,
ProductDetailsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
__________________________________________
product-list.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.less']
})
products = products;
____________________________________________
product-list.component.html
<h2>Products</h2>
<h3>
{{ product.name }}
</a>
</h3>
<p *ngIf="product.description">
Description: {{ product.description }}
</p>
</div>
________________________________________________
product-details.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.less']
})
product: Product|undefined;
constructor(
private route: ActivatedRoute,
){}
ngOnInit() {
______________________________________________
product-details.component.html
<h2>Product Details</h2>
<div *ngIf="product">
</div>
_____________________________________________
topbar.component.html
<a [routerLink]="['/']">
AIM:
Design a page to display student information using dependency Injection.
First create application with name injectionExample:
ng new injectionExample
cd injectionExample
-------------------------------------------------------------------------------------------------
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;let i=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
// product.service.ts
@Injectable({
providedIn: 'root'
})
getProducts(): Observable<any> {
return this.http.get<any>(this.apiUrl);
return this.http.get<any>(`${this.apiUrl}?q=${query}`);
}
Step 3: Create a Product Listing Component
// product-list.component.ts
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
products$: Observable<any>;
ngOnInit() {
this.fetchProducts();
fetchProducts() {
this.products$ = this.productService.getProducts();
searchProducts() {
this.products$ = this.productService.searchProducts(this.searchQuery);
}
<!-- product-list.component.html -->
<ul>
{{ product.name }}
</li>
</ul>
// app.module.ts
@NgModule({
declarations: [
AppComponent,
ProductListComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [ProductService],
bootstrap: [AppComponent]
})
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:
getStudents() {
return this.http.get('/api/students');
addStudent(student: any) {
ngOnInit() {
this.students = data;
});
}
Open the generated student-table.component.html file 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>
Open the app.component.html file and replace its content with the following code:
<app-student-table></app-student-table>
imports: [
HttpClientModule
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:
addProduct(product: any) {
Step-3 Create a component to display the product table and insert form:
onSubmit(form: NgForm) {
if (form.valid) {
this.productService.addProduct(product).subscribe(() => {
form.reset();
// Optional: Fetch the updated product list to reflect the changes in the table
this.getProducts();
});
}
}
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>
Open the app.component.html file and replace its content with the following code:
<app-product-table></app-product-table>
<div>
<router-outlet></router-outlet>
</div>
imports: [
HttpClientModule,
FormsModule
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:
practical-sevnteen.component.ts:
@Component({
selector: 'app-practical-sevnteen',
templateUrl: './practical-sevnteen.component.html',
styleUrls: ['./practical-sevnteen.component.scss']
})
export class practicalSevnteenComponent implements OnInit {
isLoggedIn: boolean = false;
username: string = '';
password: string = '';
constructor() { }
ngOnInit(): void {
}
login(): void {
// Perform login logic here, e.g., call an authentication
service
if (this.username === 'admin' && this.password === 'password') {
this.isLoggedIn = true;
}
}
logout(): void {
// Perform logout logic here, e.g., clear session or token
this.isLoggedIn = false;
}
}
practical-sevnteen.component.html:
<div class="container">
<div *ngIf="isLoggedIn; else loginView">
<h1>Welcome, User!</h1>
<button class="btn btn-dange mt-3r"
(click)="logout()">Logout</button>
</div>
<ng-template #loginView>
<!-- Login view -->
<h1>Login</h1>
<div class="row">
<form (submit)="login()">
<div class="col-md-6 mb-3">
<input type="text" [(ngModel)]="username" name="uu"
placeholder="Username" required class="form-control">
</div>
<div class="col-md-12">
<button class="btn btn-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:
@Component({
selector: 'app-practical-eighteen',
templateUrl: './practical-eighteen.component.html',
styleUrls: ['./practical-eighteen.component.scss']
})
export class PracticalEighteenComponent implements OnInit {
ngOnInit(): void {
}
}
practical-eighteen.component.html:
@Component({
selector: 'app-practical-eighteen-details',
templateUrl: './practical-eighteen-details.component.html',
styleUrls: ['./practical-eighteen-details.component.scss']
})
export class PracticalEighteenDetailsComponent implements OnInit {
productId: any;
product: any;
constructor(
private route: ActivatedRoute,
private productService: ProductService
) { }
ngOnInit() {
this.route.paramMap.subscribe((params: any) => {
this.productId = +params.get('id');
this.product = this.productService.getProduct(this.productId);
});
}
}
practical-eighteen-details.component.html:
AIM:
Design a page to load customer and Sales order data using lazy loading
technique in angular.
Customer list:
practical-nineteen-one.component.ts:
@Component({
selector: 'app-practical-nineteen-one',
templateUrl: './practical-nineteen-one.component.html',
styleUrls: ['./practical-nineteen-one.component.scss']
})
export class PracticalNineteenOneComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
practical-nineteen-one.component.html
<p>practical-nineteen-one works!</p>
Sales order:
practical-nineteen-two/practical-nineteen-two.component.ts:
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SelesorderRoutingModule { }
OUTPUT:
PRACTICAL-20
AIM:
Design a page to implement CORS concept.
practical-twenty.component.ts:
ngOnInit(): void {
this.makeCorsRequest();
}
makeCorsRequest(): void {
const url = 'https://api.example.com/data';
this.http.get(url, { responseType: 'text' })
.subscribe(
response => {
console.log('Response:', response);
},
error => {
console.log('Error:', error);
}
);
}
}
practical-twenty.component.html
<h1>CORS Example</h1>
OUTPUT: