0% found this document useful (0 votes)
7 views

Mpt Code

The document outlines various Angular components and their functionalities, including a student grading system, student registration form, and product list with filtering capabilities. It includes HTML templates and TypeScript code for managing data, user inputs, and displaying information in a structured format. Additionally, it demonstrates the use of Angular modules, forms, and pipes for effective data handling and presentation.

Uploaded by

Tannu Patel
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)
7 views

Mpt Code

The document outlines various Angular components and their functionalities, including a student grading system, student registration form, and product list with filtering capabilities. It includes HTML templates and TypeScript code for managing data, user inputs, and displaying information in a structured format. Additionally, it demonstrates the use of Angular modules, forms, and pipes for effective data handling and presentation.

Uploaded by

Tannu Patel
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/ 68

Prac 5:

app.component.html file:
<div class='panel panel-primary'>
<div class='panel-heading'>
<h1>{{title}}</h1>
</div> <br /> <br />
<div class='panel-body'>
<div class='table-responsive'> <table
border="1">
<thead> <tr>
<th>Student Name</th>
<th>Maths</th><th>Science</
th><th>English</th
<th>Total</th> <th>Grade</th>
</tr> </thead> <tbody> <tr *ngFor="let
student of students; let i = index" [ngStyle]="{
'background-color': i
% 2 === 0 ? 'coral' : 'lightgray' }">
<td>{{ student.name }}</td> <td>{{
student.maths
}}</td>
<td>{{ student.science }}</td> <td>{{
student.english
}}</td>
<td>{{ student.total }}</td> <td
[ngSwitch]="student.grade"> <span
*ngSwitchCase="'A+'">A+</span> <span
*ngSwitchCase="'A'">A</span> <span
*ngSwitchCase="'B'">B</span> <span
*ngSwitchCase="'C'">C</span> <span
*ngSwitchDefault>No Grade</span> </td>
</tr>
</tbody> </table> </div> </div> </div>
app.component.ts file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root', templateUrl:
'./app.component.html', styleUrls:
['./app.component.css'] }) export class
AppComponent { title: string ="Student Grading
System"; students = [ { name: 'John', maths: 90,
science: 85, english: 92, total: 267, grade: 'A+' },
{ name: 'Jane', maths: 80, science: 75, english:
85, total: 240, grade: 'A' }, { name: 'Tom',
maths: 70, science: 80, english: 75, total: 225,
grade: 'B' }, name: 'Lisa', maths: 65, science: 70,
english: 80, total: 215, grade: 'C' } ]; }
app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform- browser';
import { AppComponent } from
'./app.component'; @NgModule({ declarations: [
AppComponent, ], imports: [ BrowserModule ],
providers: [], bootstrap: [AppComponent]
}) export class AppModule { }
Prac 6:
student-component.component.html file:
<div class="solid"> <div class='panel panel-
primary'>
<div class='panel-heading'>
<h3>{{title}}</h3> </div>
<div class='panel-body'> <div> <input
type="number" [(ngModel)]="studentCount"
min="0" value="0"> <br />
<br /> <button (click)="updateTable()">
Update Table</button> </div> <br /> <table>
<thead>
<tr> <th>First Name</th>
<th>Last Name</th> <th>Age</th>
<th>Action</th>
</tr> </thead> <tbody> <tr *ngFor="let
student of students; let i=index;"> <td><input
type="text" [(ngModel)]="student.fname"
name="fname{{i}}"></td>
<td><input type="text"
[(ngModel)]="student.lname"
name="lname{{i}}"></td> <td><input
type="number" [(ngModel)]="student.age"
name="age{{i}}" min="0"></td> <td><button
(click)="removeStudent(i)">Remove</button></
td> </tr>
</tbody> </table> </div> </div> </div>
student-component.component.ts file:
import { Component, OnInit } from
'@angular/core'; @Component({ selector: 'app-
student-component', templateUrl: './student-
component.component.html', styleUrls:
['./student-component.component.css'] }) export
class StudentComponentComponent implements
OnInit { title: string ="Students Record" ;
studentCount: number = 0; students: Student[]
= []; ngOnInit() { console.log("init")
this.students.push(new
Student("Shweta","Patel", 21));
this.students.push(new
Student("Neha","Patel", 20));
this.students.push(new Student("Ami","Patel",
22)); this.studentCount = this.students.length; }
updateTable()
{ const currentCount = this.students.length; if
(this.studentCount > currentCount) { for (let i =
currentCount; i < this.studentCount; i++)
{ this.students.push(new Student('', '', 0)); } }
else if (this.studentCount < currentCount)
{ this.students.splice(this.studentCount); } }
removeStudent(index: number)
{ this.students.splice(index, 1); } } class Student
{ constructor(public fname: string, public lname:
string, public age: number) { } }
border: 1px solid #ddd; padding: 8px; text-align:
left; } th
{ background-color: #f2f2f2; }
input[type="number"], input[type="text"]
{ width: 100%; } .center-screen { display: flex;
justify-content: center; align-items: center; text-
align: center; } div.solid { border-style: solid;
padding: 15px;}
app.component.html file:
<app-student-component>
</app-student-component>
app.component.ts file:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl:
'./app.component.html',
styleUrls: ['./app.component.css'] }) export class
AppComponent { }
app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform-browser'; import
{ AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { StudentComponentComponent } from
'./student- component/student-
component.component';
@NgModule({ declarations: [ AppComponent,
StudentComponentComponent ],
providers: [],
bootstrap:
[AppComponent]}) export
class AppModule { }
Prac 7:
filter.pipe.ts file:
import { Pipe, PipeTransform } from
'@angular/core'; @Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform
{ transform(items: any[], searchText: string):
any[] { if (!items) { return []; } if (!searchText) {
return items; } searchText =
searchText.toLowerCase(); return
items.filter(item => { return
item.name.toLowerCase().includes(searchText); }
); } }
filter.pipe.ts file
: import { Pipe, PipeTransform } from
'@angular/core'; @Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform
{ transform(items: any[], searchText: string):
any[] { if (!items) { return []; } if (!searchText)
{ return items; } searchText =
searchText.toLowerCase(); return
items.filter(item => { return
item.name.toLowerCase().includes(searchText); }
); } }
.center-screen { display: flex; justify-content:
center; align-items: center; text-align: center; }
div.solid { border- style: solid; padding: 15px; }
product-list.component.ts file:
import { Component } from '@angular/core';
@Component({
selector: 'app-product-list', templateUrl:
'./product- list.component.html', styleUrls:
['./product- list.component.css'] })
export class ProductListComponent {
searchText: string
= ''; title: string ="Product List" ; products: any[]
= { id: 1, name: 'Cococola Classic',
purchaseDate: new Date('2022-01-01'), price:
10.99,
imageUrl: 'https://greendroprecycling.com/wp-
content/uploads/2017/04/GreenDrop_Station_Alu
minum
_Can_2-150x150.jpg' },
{ id: 2, name: 'Stainless steel water bottle',
purchaseDate: new Date('2022-02-01'), price:
20.99, imageUrl:
'https://thumbs.dreamstime.com/z/metal- water-
bottle-reusable-stainless-steel-flask-metal-water-
bottle-reusable-stainless-steel-eco-flask-mockup-
empty- aluminum-187861207.jpg' },
{ id: 3, name: 'Perfume bottles vector.',
purchaseDate: new Date('2022-03-01'), price:
30.99, imageUrl:
'https://cdn.w600.comps.canstockphoto.com/perf
ume- bottles-vector-product-clipart-
vector_csp56261954.jpg' },
{ id: 4, name: 'Men Sports Shooes Nike',
purchaseDate: new Date('2022-04-01'), price:
40.99, imageUrl: 'https://images.squarespace-
cdn.com/content/v1/5911f31c725e251d002da9ac
/16132 10424136-
AS3MY547OBB5Y3GSQ359/
Product+Photography?for mat=1000w' }
Product-list.component.html file:
<div class="solid">
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3>{{title}}</h3> </div> <br />

<div class='panel-body'> <div class='table-


responsive'>
<input type="text"
[(ngModel)]="searchText"
placeholder="Search"> <br />
<table> <thead> <tr> <th>ID</th>
<th>Name</th>
<th>Purchase Date</th>
<th>Price</th> <th>Image</th>
</tr> </thead> <tbody>
<tr *ngFor="let product of products | filter:
searchText">
<td>{{ product.id }}</td>
<td>{{ product.name | uppercase}}</td>
<td>{{ product.purchaseDate | date }}</td>
<td>{{ product.price | currency }}</td>
<td><img [src]="product.imageUrl"
height="100" width="100"></td> </tr>
</tbody> </table> </div>
</div>
</div> </div>
app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform- browser';
import { FormsModule } from
'@angular/forms'; import { AppComponent }
from './app.component';
import { ProductListComponent } from
'./product- list/product-list.component';
import { FilterPipe } from './pipes/filter.pipe';
@NgModule({ declarations: [ AppComponent,
ProductListComponent, FilterPipe ],
imports: [ BrowserModule, FormsModule],
providers: [], bootstrap: [AppComponent]
})
export class AppModule { }
Prac 8:
student-registration.component.css file:
registration-form { width: 100%; } .form
{ width: 200%; float: left; } .form-group {
margin-bottom: 10px; } body { font-family:
Arial, Helvetica, sans-serif; }
.invalid-feedback { color: red; } .success-
feedback { color: green; } input[type=text],
input[type=password], input[type=email],
input[type=number]
{ width: 100%; padding: 7px 14px; display:
inline-block; border: 1px solid #ccc; box-sizing:
border-box; } button { background-color:
#04AA6D; color: white;
padding: 14px 20px; margin: 8px 0; border:
none; cursor: pointer; width: 260%; } form {
display: table; } div
{ display: table-row; } label { display: table-
cell; } input { display: table-cell; }
Student-registration.component.html file:
<div class="registration-form">
<form #registrationForm="ngForm"
(ngSubmit)="onSubmit(registrationForm)"
class="form">
<div class="form-group"> <label
for="name">Name:</label> <input type="text"
id="name" name="name" ngModel required
minlength="2" maxlength="50" class="form-
control">
<div*ngIf="registrationForm.controls.name.errors
?.requir ed" class="invalid-feedback">
Name is required</div> <div
*ngIf="registrationForm.controls.name.errors?.mi
nlength " class="invalid-feedback">
Name cannot be more than 50 characters
long</div>
</div> <div class="form-group"> <label
for="email">Email:</label>
<input type="email" id="email" name="email"
ngModel required email class="form-control">
<div
*ngIf="registrationForm.controls.email.errors?.re
quired" class="invalid-feedback">
Email is required</div> <div
*ngIf="registrationForm.controls.email.errors?
.email" class="invalid-feedback">
Email must be a valid email address</div>
</div> <div class="form-group"> <label
for="phone">Mobile Number:</label> <input
type="number" id="phone" name="phone"
ngModel required phone class="form-
control"> <div
*ngIf="registrationForm.controls.phone.errors?.re
quired" class="invalid-feedback">Mobile is
required</div> <div
*ngIf="registrationForm.controls.phone.errors?.
phone" class="invalid-feedback">Phone
Number must be a valid Mobile Number</div>
</div> <div class="form- group"> <label
for="password">Password:</label>
<input type="password" id="password"
name="password" ngModel required
minlength="8" maxlength="20" class="form-
control"> <div
*ngIf="registrationForm.controls.password.errors
?.requir ed" class="invalid-feedback">Password
is required</div> <div
*ngIf="registrationForm.controls.password.errors?
.minle ngth" class="invalid-feedback">Password
must be at least 8 characters long</div> <div
*ngIf="registrationForm.controls.password.errors?
.maxle ngth" class="invalid-feedback">Password
cannot be more than 20 characters long</div>
</div>
<div class="form-group"> <label
for="confirmPassword">Confirm
Password:</label>
<input type="password" id="confirmPassword"
name="confirmPassword" ngModel required
minlength="8" maxlength="20" class="form-
control">
<div
*ngIf="registrationForm.controls.confirmPassword
.errors
?.required" class="invalid-feedback">
Confirm Password is required</div> <div
*ngIf="registrationForm.controls.confirmPassword
.errors
?.minlength" class="invalid-feedback">
<h1 class="success-feedback"
*ngIf="success">Data Saved Successfully</h1>
</form> </div>
student-registration.component.ts file:
import { Component } from
'@angular/core'; import { NgForm }
from '@angular/forms';
@Component({ selector: 'app-student-
registration', templateUrl: './student-
registration.component.html', styleUrls:
['./student-registration.component.css'] })
export class StudentRegistrationComponent {
success= false; onSubmit(form: NgForm)
{ console.log(form); form.reset();
this.success=true; }}
app.component.ts file:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl:
'./app.component.html', styleUrls
['./app.component.css'] })
export class AppComponent { title: string
="Student Registration Form" ; }
app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform- browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from
'./app.component';
import { StudentRegistrationComponent }
from './student-registration/student-
registration.component'; @NgModule({
declarations: [ AppComponent,
StudentRegistrationComponent ],
providers: [], bootstrap:
[AppComponent] }) export class
AppModule { }
Prac 9:
faculty-details.component.css file:
color: red; Modern Practical Tools(4340705) VPMP
Page 46 } .success-feedback { color: green; }
.form { width: 200%; float: left; }
.form-group { margin: 10; } input[type=text],
input[type=password], input[type=email],
input[type=number],
input { display: table-cell; } .innerdiv { display:
table-cell
} div.solid { border-style: solid; padding: 15px; }
.button { background-color: #04AA6D; color:
white; padding: 14px 20px; margin: 8px 0;
border: none; cursor: pointer; width: 200%; }
.button1 { background-color: #04AA6D; color:
white; padding: 12px 18px; margin: 8px 0;
border: none; cursor: pointer; width: 100%; }
faculty-details.component.ts file:
import { Component, OnInit } from
'@angular/core'; import { FormGroup,
FormBuilder, Validators, FormArray
} from '
@angular/forms'; @Component({
selector: 'app-faculty-details', templateUrl:
'./faculty- details.component.html', styleUrls:
['./faculty- details.component.css']
})
export class FacultyDetailsComponent
implements OnInit { facultyForm: FormGroup;
success= false; constructor(private formBuilder:
FormBuilder) { }
ngOnInit() { this.createForm(); } createForm()
{ this.facultyForm = this.formBuilder.group({
code: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(10)]],
name: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]], email: ['',
[Validators.required, Validators.email]], type: ['',
Validators.required], facultyStatus: ['Active',
[Validators.required]], subjects:
this.formBuilder.array([this.createSubjectTeachin
g()]) });
faculty-details.component.html file:
<div *ngFor="let subject of
facultyForm.get('subjects')['controls'];
let i = index" [formGroupName]="i">
<div> <label>Subject Name:</label>
<input type="text"
formControlName="subjectName" />
<div
*ngIf="facultyForm.get('subjects')['controls']
[i].get('subjec tName').invalid &&
facultyForm.get('subjects')['controls']
[i].get('subjectName'
).touched" class="alert alert-danger">
Please enter a valid subject name. </div> </div>
<br />
<div> <label>Teaching Hours:</label> <input
type="text"
formControlName="teachingHours" /> <div
*ngIf="facultyForm.get('subjects')['controls']
[i].get('teachi ngHours').invalid &&
facultyForm.get('subjects')['controls']
[i].get('teachingHour s').touched" class="alert
alert-danger">
Please enter a valid teaching hours. </div>
</div>
<button type="button" class="btn btn-danger
button1"
(click)="removeSubjectTeaching(i)">-</button>
</div>
</div>
<button type="button" class="btn btn-primary
button1" (click)="addSubjectTeaching()">Add
Subject</button>
<button type="submit" [disabled]="!
facultyForm.valid"
class="button">Submit</button> <h3
class="success- feedback" *ngIf="success">Data
Saved Successfully</h3> </form>
app.component.html file:
<div class="solid"> <div class='panel panel-
primary'>
<div class='panel-heading'>
<h3>{{title}}</h3> </div> <br />
<app-faculty- details></app-faculty-
details> </div> </div>
app.component.ts file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root', templateUrl:
'./app.component.html', styleUrls:
['./app.component.css'] })
export class AppComponent
{ title: string ="Faculty
Details" ; }
app.component.css file:
.center-screen { display: flex; justify-content:
center; align-items: center; text-align:
center; }
div.solid { border-style: solid; padding: 15px; }
app.module.ts file:
import { NgModule } from
'@angular/core'; import
{ BrowserModule } from
'@angular/platform-browser';
import { FormsModule, ReactiveFormsModule }
from '@angular/forms';
import { AppComponent } from
'./app.component';
import { FacultyDetailsComponent } from
'./faculty- details/faculty-details.component';
@NgModule declarations: [ AppComponent,
FacultyDetailsComponent ],
imports: [ BrowserModule, FormsModule,
ReactiveFormsModule ],
providers: [], bootstrap: [AppComponent]
}) export class AppModule { }
Prac 10:
product.component.css file:
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px;
text-align: left; } th { background-color:
#f2f2f2; }
input[type="text"] { border: 2px solid blue;
border-radius: 4px; padding: 12px; margin-
bottom: 10px;
margin-right: 10px; } input[type="number"],
input[type="text"] {
width: 98%; .center-screen { display: flex;
justify- content: center; align-items: center; text-
align: center; }
div.solid { border-style: solid; padding: 15px; }
product.component.ts file:
import { Component, EventEmitter, Input,
Output } from '@angular/core';
import { Product } from '../product.interface';
@Component({ selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css'] })
export class ProductComponent { @Input()
product: Product; @Output() addToCartEvent =
new EventEmitter<Product>();
addToCart()
{ this.addToCartEvent.emit(this.product); } }
product-list.component.css file:
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px;
text-align: left; } th { background-color:
#f2f2f2; }
input[type="text"] { border: 2px solid blue;
border-radius: 4px; padding: 12px; margin-
bottom: 10px;
margin-right: 10px; } input[type="number"],
input[type="text"] { width: 98%; } .center-
screen { display: flex; justify-content: center;
align-items:
center; text-align: center; } div.solid { border-
style: solid; padding: 15px; }
product-list.component.html file:
<div class="cart"> <div class="cart-items">
<h4>Products</h4> <app-product *ngFor="let
product of products" [product]="product"
(addToCartEvent)="addToCart($event)"></app-
product>
</div> <br /> <div class="cart-total">
<h4>Summary</h4> <table> <thead> <tr>
<th>Image</th> <th>Name</th>
<th>Description</th>
<th>Price</th>
td></td> <td><h5 class="card-
title">{{getTotalAmount()}}</h5></td>
</tr> </tbody>
</table> </div> </div>
product-list.component.ts file:
import { Component } from '@angular/core';
import { Product } from '../product.interface';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css'] })
export class ProductListComponent { products:
Product[] = [ { name: 'Cococola Classic',
description:
{ name: 'Men Sports Shooes Nike', description:
'This is Men Sports Shooes Nike Product', price:
40.99, image: 'https://images.squarespace-
cdn.com/content/v1/5911f31c725e251d002da9ac
/16132 104245Y3GSQ359/Product+Photography?
format=1000 w' }, { name: 'Apple Smart Watch',
description: 'This is Apple Smart Watch Product',
price: 100.99, image:
'https://images.unsplash.com/photo-1546868871-
7041f2a55e12?ixlib=rb-
4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlf
Hx8f
GVufDB8fHx8&auto=format&fit=crop&w=464&q
=80' }, { name: 'Sony Camera', description: 'This
is Sony Camera Product', price: 60.99, image:
'https://images.pexels.com/photos/90946/pexels-
photo- 90946.jpeg?
auto=compress&cs=tinysrgb&w=1260&h=7
50&dpr=1' }, ]; cart: Product[] = [];
addToCart(product: Product)
{ console.log('Adding to cart: ', product);
this.cart.push(product); // Add product to cart
here } getTotalAmount() { const totalAmount =
this.cart.reduce((total, item) => total +
item.price, 0) return this.roundUp(totalAmount,
2) } roundUp(num: any, precision: any)
{ precision = Math.pow(10, precision) return
Math.ceil(num * precision) / precision } }
app.component.html file:
<div class='panel panel-primary'>
<div class='panel-heading'>
<h2>{{title}} </h2> </div> <br />
<br /> <app-product-list>
</app-product-list> </div>

app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform- browser';
import { AppComponent } from
'./app.component';
import { ProductComponent } from
'./product/product.component';
import { ProductListComponent } from
'./product- list/product-list.component';
@NgModule({ declarations: [ AppComponent,
ProductComponent, ProductListComponent, ],
imports: [ BrowserModule ], providers: [],
bootstrap: [AppComponent] }) export class
AppModule { }
Prac 11:
lifecycle-child.component.ts
import { Component, OnInit, Input, Output,
EventEmitter, OnChanges, DoCheck,
AfterViewInit, OnDestroy }
from '@angular/core';
@Component({ selector: 'app-lifecycle-child',
templateUrl: './lifecycle-child.component.html',
styleUrls: ['./lifecycle-child.component.css'] })
export class LifecycleChildComponent
implements OnInit, OnChanges, DoCheck,
AfterViewInit, OnDestroy
{ @Input() childProp: string;
@Output() childEvent = new
EventEmitter<string>(); showNgDoCheck =
false; constructor() { }
{ this.log('ngOnDestroy');
this.childEvent.emit('Child Component
ngOnDestroy Triggered'); } triggerEvent()
{ this.childEvent.emit('Child Event Triggered'); }
private log(hook: string)
{ console.log(`LifecycleChildComponent $
{hook}`); }}
lifecycle-child.component.html
<p >Child Component Property: </p> <p
[innerHTML]="childProp"></p>
<button (click)="triggerEvent()">Trigger
Event</button>
lifecycle-child.component.ts
import { Component, ChangeDetectorRef, OnInit,
OnChanges, DoCheck, AfterViewInit, OnDestroy }
from '@angular/core';
@Component({ selector: 'app-lifecycle-demo',
templateUrl: './lifecycle-demo.component.html',
styleUrls: ['./lifecycle-demo.component.css'] })
export class LifecycleDemoComponent
implements OnInit, OnChanges, DoCheck,
AfterViewInit, OnDestroy
{ showChild = false; parentProp = 'Initial Parent
Value'; childText = 'Child Component'; message
= ''; constructor(private cdr: ChangeDetectorRef)
{}
ngOnInit() { this.log('ngOnInit');
} ngOnChanges() { this.log('ngOnChanges'); }
ngDoCheck() { this.log('ngDoCheck'); }
ngAfterViewInit() { this.log('ngAfterViewInit'); }
app.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl:
'./app.component.html',
styleUrls: ['./app.component.css'] }) export class
AppComponent { title: string ="Angular
Component Lifecycle Demo" ; }
app.module.ts
import { NgModule } from '@angular/core';
import {
BrowserModule } from
'@angular/platform-
browser';
import { AppComponent } from
'./app.component';
import { LifecycleDemoComponent } from
'./lifecycle- demo/lifecycle-demo.component';
import { LifecycleChildComponent } from
'./lifecycle- child/lifecycle-child.component';
@NgModule({
declarations: [ AppComponent,
LifecycleDemoComponent,
LifecycleChildComponent ], imports:
[ BrowserModule ]
, providers: [], bootstrap: [AppComponent]
}) export class AppModule { }
Prac 12:
product-details.component.html
<div class="card">
<div class="card-body"> <br /> <br /> <table>
<thead>
<tr> <th>Image</th> <th>Name</th>
<th>Description</th> <th>Price</th>
</tr> </thead> <tbody> <tr> <td>
<img class="product-image"
[src]="product.image" height="100"
width="100"></td>
<td><h5 class="card-title">{{ product.name
}}</h5></td> <td><p class="card-
text">{{ product.description }}</p></td>
<td><p class="card-text">{{ product.price |
currency
}}</p></td> </tr> </tbody> </table>
</div></div>
product-details.component.ts
import { Component, OnInit
} from '@angular/core';
import { ActivatedRoute } from
'@angular/router';
import { ProductService } from
'../product.service'; @Component({ selector:
'app-product-detail', templateUrl:
'./product-detail.component.html', styleUrls:
['./product- detail.component.css'] })
export class ProductDetailComponent
implements OnInit { product = { id: '', name: '',
description: '', price: 0, image: '' };
constructor( private route:
ActivatedRoute, private productService:
ProductService
) { } ngOnInit()
{ console.log("Product Details ng Onit") const id
= this.route.snapshot.paramMap.get('id');
this.product =
this.productService.getProductById(id); }}
product-list.component.ts
import { Component, OnInit
} from '@angular/core';
import { ProductService } from
'../product.service'; import { Product } from
'../product.interface';
@Component({ selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product- list.component.css'] })
export class ProductListComponent implements
OnInit { products = []; constructor(private
productService: ProductService) { }
ngOnInit() { this.products =
this.productService.getProducts();
console.log("ngOnInit this.products === ",
this.products);
}}
app.component.html
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3>{{title}}</h3>
</div> <div class='panel-body'> <router-
outlet>
</router-outlet></div></div>
app.component.ts
import { Component } from
'@angular/core';
@Component({ selector: 'app-root',
templateUrl: './app.component.html', styleUrls:
['./app.component.css'] })
export class AppComponent { title: string
="Product Information" ; movies: Movie[] =[
{title:'Zootopia',director:'Byron Howard, Rich
Moore',cast:'Idris Elba, Ginnifer Goodwin, Jason
Bateman',releaseDate:'March 4, 2016'}
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 { ProductDetailComponent } from
'./product- detail/product-detail.component';
import { RouterModule }
import { AppRoutingModule } from
'./app.routing.module';
@NgModule({ declarations: [ AppComponent,
ProductListComponent, ProductDetailComponent,
], imports: [ BrowserModule, RouterModule,
AppRoutingModule ], providers: [], bootstrap:
[AppComponent] })
export class AppModule { }
.products.find(product => product.id === id); }
} constructor() { }
getProducts()
{ console.log("this.products === ",
this.products); return this.products; }
getProductById(id: string)
{ return this.products.find(product => product.id
=== id);
}}
Prac 13:
student-list.component.html
<h3>Student List</h3> <table>
<thead> <tr> <th>Name</th> <th>Age</th>
<th>Class</th> </tr> </thead> <tbody>
<tr *ngFor="let student of students">
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.class }}</td>
</tr> </tbody> </table>
student-list.component.ts
import { Component, OnInit
} from '@angular/core';
import { StudentService } from
'../student.service'; @Component({
selector: 'app-student-list', templateUrl:
'./student- list.component.html', styleUrls:
['./student- list.component.css'] })
export class StudentListComponent implements
OnInit { students = [];
constructor(private studentService:
StudentService) { } ngOnInit() { this.students =
this.studentService.getStudents(); } }
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform- browser';
import { AppComponent } from
'./app.component';
import { StudentListComponent } from
'./student- list/student-list.component';
@NgModule({ declarations: [ AppComponent,
StudentListComponent ],
imports: [ BrowserModule ], providers: [],
bootstrap: [AppComponent]
student.service.ts
import { Injectable }
from '@angular/core';
@Injectable({ providedIn:
'root' }) export class
StudentService
{ students = [ { name: 'John Doe', age: 20, class:
'1A' }, {
name: 'Jane Smith', age: 19, class: '2B' }, {
name: 'Bob
Johnson', age: 21, class: '3C'
} ]; constructor() { }
getStudents()
return this.students; } }
Prac 14:
Package.json
{ "start": "node index.js", "test": "echo \"Error:
no test specified\" && exit 1" }, "author":
"Saurabh Pathak",
"license": "ISC", "dependencies": { "cors":
"^2.8.5",
"express": "^4.17.1", "lodash": "^4.17.21",
"moment":
"^2.29.4", "mysql2": "^3.2.0" } }
product.controller.js
const moment =
require('moment'); const
{ Constants:
{ RESPONSE_STATUS_CODE: { BAD_REQUEST,
SUCCESS, INTERNAL_SERVER_ERORR },
RESPONSE_MESSAGE: {
BAD_REQUEST_MESSAGE,
INTERNAL_SERVER_MESSAGE }, } } =
require("../utils/constant")
const productServices =
require("../services/product.services")
exports.searchProduct = (req, res, next) =>
{ try { let { keyword } = req.query; let error =
[]; if(error.length > 0) { res.body =
{ statusCode: BAD_REQUEST,
message: BAD_REQUEST_MESSAGE, error: error
} next(); } const products =
productServices.searchProduct(keyword);
console.log("products ==== ", products);
res.body = { statusCode: SUCCESS, message:
`product list retrieved`, data: products
} next(); }
catch(err) { console.log("err", err); res.body = {
statusCode:
INTERNAL_SERVER_ERORR, message:
INTERNAL_SERVER_MESSAGE, error: err } next();
}}
Product-listing.component.html
<div class="solid">
<div class='panel panel-primary'> <div
class='panel- heading'> <h3>{{title}}</h3>
</div> <br /> <div class='panel-body'>
<div class='table-responsive'>
<input type="text" placeholder="Search
products" (keyup)="onSearch($event)">
<br /> <table> <thead> <tr>
<th>ID</th> <th>Name</th>
<th>Description</th> <th>Price</th>
<th>Image</th> </tr> </thead>
<tbody> <tr *ngFor="let product of products">
<td>{{ product.id }}</td>
<td>{{ product.name | uppercase}}</td>
<td>{{ product.description }}</td>
<td>{{ product.price | currency }}</td>
<td><img [src]="product.image" height="100"
width="100"></td>
</tr> </tbody> </table> </div>
</div> </div>
</div>
product-listing.component.css
table { border-collapse: collapse; width: 100%; }
th,
td { border: 1px solid #ddd; padding: 8px; text-
align: left;
} th { background-color: #f2f2f2; }
input[type="text"] { border: 2px solid
blue;

border-radius: 4px; padding: 12px; margin-


bottom: 10px; margin-right;
} input[type="number"], input[type="text"] {
width: 98%; }
.center-screen { display: flex; justify-
content: center; align-items: center; text-
align: center; } 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 =
'http://localhost:8080/';
constructor(private http: HttpClient) { }
getProducts():
Observable<any[]>
{ return this.http.get<any[]>(`$
{this.apiUrl}product/search`); }
searchProducts(keyword: string):
Observable<any[]>
{ return this.http.get<any[]>(`$
{this.apiUrl}product/search?keywo rd=$
{keyword}`); } }
Prac 15:
Package.json {
{ "start": "node index.js", "start-prod": "pm2
start index.js", "test":
"echo \"Error: no test specified\" && exit 1" },
"author": "Saurabh Pathak",
"license": "ISC", "dependencies":
{ "cors": "^2.8.5","express": "^4.17.1", "lodash":
"^4.17.21", "moment": "^2.29.4", "mysql2":
"^3.2.0" }}
Database.js
getConnection()
{ const { database:
{ host, user, password, database, port
} } return await
pool.getConnection(); }
const connection = await getConnection();
try { const [rows] = await
connection.query(query, params); //
console.log("[rows] === ", rows)
connection.release(); return rows; } finally
{ connection.release(); } }
executeQuery(query, [...values, ...values]); }
catch(error)
{ throw new Error(error) } } module.exports =
{ executeQuery, checkRecordExist };
app.component.ts
import { Component }
from '@angular/core';
@Component({
selector: 'app-root', templateUrl:
'./app.component.html', styleUrls:
['./app.component.css'] })
export class AppComponent { title: string
="Student Data" ; }
res.body || {}; res.body.statusCode =
res.body.statusCode || 200;
res.status(res.body.statusCode);
res.json(res.body); }; module.exports =
{ response }
app.module.ts
import { NgModule } from
'@angular/core';
import { BrowserModule } from
'@angular/platform-browser'; import
{ FormsModule,ReactiveFormsModule } from
'@angular/forms';
import { HttpClientModule } from
'@angular/common/http'; import {
AppComponent } from './app.component';
import { StudentDataComponent } from
'./student- data/student-data.component';
import { StudentAddComponent } from
'./student- add/student-add.component';
import { AppRoutingModule }
from './app.routing.module';
@NgModule({
declarations: [ AppComponent,
StudentDataComponent, StudentAddComponent,
],
imports: [ BrowserModule, HttpClientModule,
FormsModule, ReactiveFormsModule,
AppRoutingModule, ],
providers: [], bootstrap:
[AppComponent] }) export class
AppModule { } student.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from
'@angular/common/http'; import { Observable }
from 'rxjs';
@Injectable({ providedIn: 'root' })
export class StudentService { private apiUrl =
'http://localhost:8080/';
constructor(private http: HttpClient) { }
getStudents():
table { border-collapse: collapse; width: 100%; }
th,
td { border: 1px solid #ddd; padding: 8px; text-
align: left;
} th { background-color:
#f2f2f2; } input[type="text"]
{ border: 2px solid
blue; border-radius:
4px; padding: 12px;
margin-bottom:
10px; margin-
right: 10px; }
const routes: Routes = [ { path: '', component:
StudentDataComponent },
{ path: 'student', component:
StudentDataComponent },
{ path: 'student/add',
component: StudentAddComponent } ];
@NgModule({
imports: [ CommonModule, BrowserModule,
RouterModule.forRoot(routes,{ useHash: true })
],
exports
input[Observable<any[]>
{ return this.http.get<any[]>(`$
{this.apiUrl}student`); } saveStudent(student:
any)
{ return this.http.post<any[]>(`$
{this.apiUrl}student`, student); } }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy