Aditya College Engineering Vision & Mission
Aditya College Engineering Vision & Mission
VISION:
To induce higher planes of learning by imparting technical education with
✓ International standards
✓ Applied research
✓ Creative Ability
✓ Value based instruction and to emerge as a premiere institute
MISSION:
VISION:
MISSION:
Exercise -1
1a) Observe the link [Link] on which the mCart application
is running. Perform the below activities to understand the features of the
application.
# Install Angular CLI globally if not already installed npm
install -g @angular/cli@16.0.0
# Create a new Angular project named 'mcart' ng
new one
# Navigate into the project folder cd
one
#Create a new component ng
generate component welcome
PROGRAM :
#[Link]
<div class="welcome-container">
<h1>Welcome to mCart!</h1>
<p>
<button class="login-
button">Login</button
>
<footer class="footer-text">
<div>
Designed by 22MH1A05D1
</div></footer>
#[Link]
import { Component } from '@angular/core'; @Component({
templateUrl: '[Link]', styleUrls:
['[Link]']
})
export class WelcomeComponent {
public pageTitle = 'Welcome';
constructor() {
}
#[Link]
<app-welcome></app-
welcome> #To run the
Application ng serve
OUTPUT:
Designed by 22MH1A05D1
1b) Create a new component called hello and rendering Hello Angular on the page
imports: [BrowserModule,AppRoutingModule],
OUTPUT:
1c) Add an event to the hello component template and when it is clicked, it should change the
courseName.
#Create a new component ng
generate component hello
PROGRAM :
#[Link]
<h1>Welcome</h1>
<footer>
<div> Designed by 22MH1A05D1 </div>
</footer>
#[Link]
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello', templateUrl: "./[Link]",
styleUrls: ['./[Link]']
})
export class HelloComponent implements
OnInit { courseName = "Angular";
constructor() { } ngOnInit() {
} changeName() {
[Link] =
"TypeScript”;
}
}
#[Link]
p { color:blue; font- size:20px; } p { cursor: pointer; } p:hover { text- decoration:
}
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './app- [Link]'; import {
AppComponent } from './[Link]'; import {
HelloComponent } from './hello/[Link]';
@NgModule({
imports:
[BrowserModule,AppRoutingModule],
declarations: [AppComponent,
OUTPUT:
Exercise -2
2a) Create a login form with username and password fields. If the user enters the correct
credentials, it should render a "Welcome <<username>>" message otherwise it should
render "Invalid Login!!! Please try again...".
PROGRAM:
#[Link]
<div *ngIf="!submitted" class="main">
<h2 class="title">Login Form</h2>
<form>
<label>Username</label>
<input type="text" #username /><br /><br />
<label for="password">Password</label>
<input type="password" name="password" #password /><br />
</form>
<ng-template #failureMsg>
<h4 id="failureMsg">Invalid Login !!! Please try again...</h4>
</ng-template>
<footer>
Designed by 22MH1A05D1
</footer>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]'],
})
export class AppComponent {
isAuthenticated!: boolean; submitted
= false;
padding: 8px;
margin- bottom:
10px; box- sizing:
border-box;
} button {
background-color:
#1d1d1d; color:
white; padding:
10px 40px; border:
none; border-
radius: 5px; cursor:
pointer; margin-top:
20px;
}
button[type="butt
on"] { background-
color: #f44336; } h4
{ color: #333; font-
size: 40px; }
div[ngIf="submitte
d"] { margin-top:
20px; } ng- template
{ display: block;
margin-top: 10px;
}
#failureMsg {
color: #f44336;
}
OUTPUT:
Welcome Sri
2b) Creating a courses array and rendering it in the template using ngFor directive
in a list format.
PROGRAM:
#[Link]
<div class="container">
<h2>Available Courses</h2>
<ul>
<li *ngFor="let course of courses; let i = index">
{{ i + 1 }} - {{ [Link] }}
</li>
</ul>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
OUTPUT:
2C) Display the correct option based on the value passed to ngSwitch directive.
PROGRAM:
#[Link]
<div class="container">
<h3>Display Using ngSwitch Directive</h3>
<h4>Current choice is {{ choice }}</h4>
<div [ngSwitch]="choice">
<p *ngSwitchCase="1">First Choice</p>
<p *ngSwitchCase="2">Second Choice</p>
<p *ngSwitchCase="3">Third Choice</p>
<p *ngSwitchDefault>Default Choice</p>
</div>
<footer>
Designed by 22MH1A05D1
</footer>
</div>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class AppComponent
{ choice = 0; nextChoice() {
[Link]++;
}
}
OUTPUT:
2D) Create a custom structural directive called 'repeat' which should repeat the
element given a number of times.
PROGRAM:
#Generate a directive in terminal ng generate
directive repeat
#[Link]
<div class="container">
<h2>{{ title }}</h2>
<h3>Structural Directive: *appRepeat</h3>
<p *appRepeat="9">23MH5A0510...</p>
<footer>
DesignedBy<strong>22MH1A05D1</strong>
</footer>
</div>
#[Link]
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({
selector:
'[appRepeat]'
})
export class RepeatDirective { constructor(private templateRef:
TemplateRef<any>, private viewContainer:
ViewContainerRef) { }
@Input() set appRepeat(count: number) { for
(let i = 0; i < count; i++) {
[Link]([Link]);
}}}
OUTPUT:
Exercise-3
paddingValue = '10px';
3B) Applying multiple CSS classes to the text using ngClass directive
PROGRAM:
#[Link]
<article class="card">
<p
class="demo-paragraph"
[ngClass]="{ 'blue-text': isBlueText, 'bold-text': isBoldText, 'wide-paragraph': isWideParagraph }"
>
From the first click to the final interaction, the design tells a story, ensuring that every
user feels not just engaged, but truly understood in the digital space.
</p>
</article>
</div>
<footer class="footer">
<span>Desined by 22MH1A05D1</span>
</footer>
#[Link]
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
imports: [CommonModule],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class App {
.header {
display: grid;
gap: 4px;
}
OUTPUT:
3C) Create an attribute directive called 'showMessage' which should display the
given message in a paragraph when a user clicks on it and should change the text
color to red
PROGRAM:
#Generate a directive in terminal ng
generate directive message
#[Link]
})
export class MessageDirective {
@Input('appMessage') message!: string;
constructor(private el: ElementRef, private renderer: Renderer2) { [Link]([Link],
'cursor', 'pointer');
}
@HostListener('click') onClick() {
[Link] = [Link];
[Link]([Link], 'color', 'red');
}
}
#[Link]
<h3>Attribute Directive</h3>
<p [appMessage]="myMessage">Click Here</p>
#[Link].c:
h3 { color: #369;
font-family: Arial, Helvetica, sans-serif; font-
size: 250%;
} p { color:
#ff0080;
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
myMessage = 'Hello, I am from attribute directive';
}
OUTPUT:
Exercise-4
#[Link]
import { Component } from
'@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
}) export class AppComponent
{ cardData
=[{
imageUrl: 'assets/imgs/[Link]',
description: 'Subway Station',
cityName: 'New york City'
}, {
imageUrl: 'assets/imgs/[Link]',
description: 'Beautiful city view',
cityName: 'Tokyo'
}, {
imageUrl: 'assets/imgs/[Link]', description:
'Festival Of Lights', cityName: 'India'
}
}
OUTPUT:
#[Link]
table { width: 20%; border-collapse: collapse; margin-top: 20px;
}
th, td{
border: 1px solid #dddddd; text-align: left; padding: 8px;
}
th { background-color: #f2f2f2;
} #[Link]
import { Component } from
'@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
4C) Binding an element using inline style and user actions like entering text in input fields.
PROGRAM:
#[Link]
<div class="grocery-list">
<h2>Grocery List</h2>
<ul>
<li *ngFor="let item of groceryItems">
{{ [Link] }} - {{ [Link] }}</li></ul>
<div class="add-item">
<label for="itemName">Item Name:</label>
<input type="text" id="itemName" [(ngModel)]="newItemName" placeholder="Enter
item name">
<label for="itemQuantity">Quantity:</label>
<input type="number" id="itemQuantity" [(ngModel)]="newItemQuantity" placeholder="Enter
quantity">
<button (click)="addItem()">Add Item</button>
</div>
<div class="credit">Designed by 22MH1A0539</div>
</div>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
groceryItems: { name: string, quantity: number }[] = [
{ name: 'Apples', quantity: 5 },
{ name: 'Bananas', quantity: 10 },
{ name: 'Milk', quantity: 2 }
];
newItemName: string = '';
newItemQuantity: number = 0;
addItem() {
if ([Link] && [Link] > 0) {
[Link]({
name: [Link],
quantity:
[Link]
}); [Link] = '';
[Link]
= 0; }}}
#[Link]
:host { display: flex; justify-
content: center; align-items:
margin-bottom: 8px;
} .add-item {
Margin-top:
20px;
} label { display:
block; margin-
bottom: 5px; font-
weight: bold;
} input { width:
100%; padding: 8px;
margin-bottom: 10px;
box-sizing: border-
box;
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser'; import {
AppRoutingModule } from './app- [Link]'; import {
AppComponent } from './[Link]'; import {
FormsModule } from '@angular/forms';
@NgModule({ declarations:
[AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]
})
export class AppModule {
OUTPUT:
Exercise -5
5A) Display the product code in lowercase and product name in uppercase using built-in pipes.
PROGRAM:
#[Link]
{{ title | titlecase}}
Product Code {{ productCode | lowercase }}
Product Name {{ productName | uppercase }}
#[Link]
table { width: 20%;
border collapse:
collapse; margin-top: 20px;
font-family: 'Segoe UI', sans-serif; }
th,
td { padding: 10px;
text-align: left;
border: 1px solid #ddd; }
th {
background-color: #f2f2f2; }
#[Link]
import { Component } from '@angular/core'; 30
@Component({
selector: 'app-root',
templateUrl: './
[Link]',
styleUrls: ['./[Link]'] })
export class
AppComponent {
title = 'product details';
productCode = 'pROD_001';
productName
OUTPUT:
})
export class AppModule { }
OUTPUT:
5C) Load CourseslistComponent in the root component when a user clicks on the
View courses list button.
PROGRAM:
#Create a new component ng
selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class CoursesListComponent { courses
=[
{ courseId: 1, courseName: "Node JS" },
{ courseId: 2, courseName: "Typescript" },
{ courseId: 3, courseName: "Angular" },
{ courseId: 4, courseName: "React JS" }
];
}
#[Link]
<h2>Popular Courses</h2>
<button (click)="show = true">View Courses list</button><br /><br />
<div *ngIf="show">
<app-courses-list></app-courses-list>
</div>
#[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class AppComponent {
show!: boolean;
}}
OUTPUT:
Exercise -6
6A) Creating an AppComponent that displays a dropdown with a list of courses as
values in it. Create another component called the Courses List component and load it
in
AppComponent which should display the course details. When the user selects a course
from the dropdown, corresponding course details should be loaded.
PROGRAM:
#Create a new component
ng generate component coursesList
#[Link]
<table border="1" *ngIf="[Link] > 0">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of course">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</tbody>
</table>
#[Link] import { Component,
Input } from '@angular/core';
@Component({
selector: 'app-courses-list', templateUrl:
'./[Link]', styleUrls:
['./[Link]'],
})
export class CoursesListComponent { courses
=[
OUTPUT:
6B) Create an AppComponent that loads another component called the courses List
component. Create another component called CoursesListComponent which should
display the courses list in a table along with a register button in each row. When a user
clicks on the
register button, it should send that courseName value back to AppComponent where it
should display the registration successful message along with courseName
PROGRAM:
#Create a new component ng
generate component coursesList
#[Link]
<table border="1">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
<td><button (click)="register([Link])">Register</button></td>
</tr>
</tbody>
</table>
#[Link]
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({
selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class CoursesListComponent {
OUTPUT:
[Link]
<div>
<h2>Grocery List</h2>
<table>
<thead>
<tr>
<th>Item</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of groceryItems">
<td>
<app-grocery-item [item]="item"></app-grocery-item>
</td>
</tr>
</tbody>
</table>
</div>
#[Link]
import { Component, ViewEncapsulation } from '@angular/core'; @Component({
selector: 'app-grocery-list', templateUrl:
'./[Link]', styleUrls:
['./[Link]'],
encapsulation:
[Link],
})
export class GroceryListComponent {
groceryItems: string[] = ['Apples', 'Bananas', 'Milk', 'Bread'];
}
#[Link] div
{ margin:
20px;
} h2 { color: #333; }
table { width: 10%;
border-collapse:
collapse; margin-top:
10px;
} th, td { border: 1px
solid #ddd; padding:
8px; text-align: left;
} th
{
background-color: #f2f2f2;
}
#[Link]
<app-grocery-list></app-grocery-list>
#[Link]
<span>{{ item }}</span>
#grocery-
[Link] span {
padding: 5px; margin-
right: 5px;
}
#[Link]
OUTPUT:
6D) Override component life-cycle hooks and logging the corresponding messages to
understand the flow.
#Create a new component ng
generate component child
Program :
#[Link]
<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]="data" />
<app-child [title]="data"></app-child>
</div>
#[Link]
import {
Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit,
AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-root', styleUrls:
['./[Link]'], templateUrl:
'./[Link]'
})
export class AppComponent implements OnInit, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy { data = 'Angular';
ngOnInit() { [Link]('Init');
}
ngDoCheck(): void {
[Link]('Change detected');
}
ngAfterContentInit(): void {
[Link]('After content init');
}
ngAfterContentChecked(): void { [Link]('After
content checked');
} ngAfterViewInit(): void {
[Link]('After view
init');
} ngAfterViewChecked(): void {
[Link]('After view
checked');
} ngOnDestroy():
void {
[Link]('Destroy'
);
}
}
#[Link] div { width:
500px; margin: 0 auto; margin-top:
10%; padding: 20px; border: 1px
solid #ccc; border-radius: 8px; box-
shadow: 0 0 10px rgba(0, 0, 0, 0.1);
font-family: 'Segoe UI', sans-serif;
} h1 { color: blue; } input { width: 50%;
padding: 10px;
margin-top:
10px;
box- sizing:
border- box;
} app-child {
margin-top:
20px;
}
#[Link]
<h3>Child Component</h3>
<h2>{{title}}</h2>
#[Link]
import { Component, OnChanges, Input } from '@angular/core'; @Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ChildComponent implements OnChanges {
@Input() title!: string;
ngOnChanges(changes: any): void {
[Link]('changes in child:' + [Link](changes));
}
}
#[Link] s
h2 { color: red;
}
#Ensure FormsModule is present in the imports section of the [Link]
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
]
OUTPUT:
Exercise -7
7 A) Create a course registration form as a template-driven form.
#Create a new component
ng generate component course-registration
Program :
#[Link]
<div class="container">
<h2>Course Registration Form</h2>
<form #registrationForm="ngForm" (ngSubmit)="onSubmit(registrationForm)">
<div class="form-group">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName" ngModel required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel required email>
</div>
<div class="form-group">
<label for="courseName">Course Name:</label>
<input type="text" id="courseName" name="courseName" ngModel required>
</div>
<div class="form-group">
<label for="Add">Address :</label>
<input type="text" id="Add" name="Add" ngModel required>
</div>
<button type="submit" [disabled]="![Link]">Submit</button>
</form>
</div>
#[Link] import
{ Component } from '@angular/core';
@Component({
selector: 'app-course-registration',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class
CourseRegistrationComponent {
onSubmit(form: any): void { if
([Link]) {
block; margin-
bottom: 8px;
color: #555; }
input { width:
100%;
padding: 8px;
box- sizing:
border-box;
border: 1px
solid #ccc;
border- radius:
4px; } button
{ background-
color:
#4caf50;
color: #fff;
padding: 10px
15px; border:
none; border-
radius: 4px;
cursor:
pointer; font-
size: 16px;
width: 100%;
}
button:disabl ed
{
background-
color: #ddd;
cursor: not-
allowed; }
.ng-
valid[require
d] { border-
left: 5pxsolid
#42A948; }
.ng-
invalid:not(fo
rm) { border-
left: 5px solid
#a94442;
}
#[Link]
<app-course-registration></app-course-registration>
#[Link]
import { NgModule } from '@angular/core'; import {
BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-
[Link]'; import { AppComponent } from
'./[Link]'; import {
CourseRegistrationComponent } from './course-
registration/[Link]';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({
declarations: [ AppComponent,
CourseRegistrationComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]
})
export class AppModule { }
output:
#registration- [Link]
<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control"
formControlName="firstName"> <div
*ngIf="[Link]['firstName'].errors" class="alert alert- danger">
Firstname field is invalid.
<p
*ngIf="[Link]['firstName'].errors?.['required']"> This field
is required!
</p>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName">
<div *ngIf="[Link]['lastName'].errors" class="alert alert- danger">
Lastname field is invalid.
<p
*ngIf="[Link]['lastName'].errors?.['required']"> This field
is required!
</p>
</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</fieldset>
</div>
<button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>
</form>
<br/>
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p>First Name: {{ [Link]('firstName')?.value }} </p>
<p> Last Name: {{ [Link]('lastName')?.value }} </p>
<p> Street: {{ [Link]('[Link]')?.value }}</p>
<p> Zip: {{ [Link]('[Link]')?.value }} </p>
<p> City: {{ [Link]('[Link]')?.value }}</p>
</div>
</div>
#[Link] import {
Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({
'./[Link]', styleUrls:
['./[Link]']
})
export class RegistrationFormComponent implements OnInit {
registerForm!: FormGroup; submitted!:boolean;
} label { display:
block; margin-
bottom: 5px;
: #721c24; background-
color: #f8d7da; border: 1px
solid #f5c6cb; padding:
8px; margin-top: 5px;
border- radius: 4px; } .btn-
primary { background-
color: #1d1d1d; color: #fff;
border: none; padding: 10px
40px; border-radius: 4px;
cursor: pointer; } .btn-
primary:hover {
background-color: #0056b3;
} [hidden] { display:
none; } h3 { margin-
bottom: 10px;} .ng-
valid[required] {
border-left: 5px solid
#42A948; }
Output :
7C) Create a custom validator for an email field in the employee registration
form ( reactive form)
Program :
#[Link]
<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</fieldset>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" formControlName="email" />
<div *ngIf="[Link]['email'].errors" class="alert alert- danger">
Email field is invalid.
.form-group {
margin-bottom: 20px;
} label { display: block; margin- bottom:
RegistrationFormComponent } from
'./registration-form/[Link]';
@NgModule({
declarations: [ AppComponent,
RegistrationFormComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule
],
providers: [], bootstrap:
[AppComponent]
})
export class AppModule { }
#To run the Application ng
serve
OUTPUT
Exercise - 8
8A) Create a custom validator for the email field in the course registration form.
in src/app as [Link]
Program :
#[Link]
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export
function emailValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => { if
(![Link]) {
return null;
} const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA- Z]{2,}$/;
const isValid = [Link]([Link]); return isValid ? null : {
invalidEmail: true };
};
}
#[Link]
</div>
<div *ngIf="[Link]('email')?.hasError('invalidEmail')"
class="errormessage">
Invalid email address.
</div>
</div>
<button type="submit" class="button">Submit</button>
</form>
#[Link]
form {
max-width: 400px; margin:
50px; padding: 20px; border:
1px solid #ccc; border-
radius: 5px;
}
.error-message { color:
red; margin-top: 8px;
}
.button { background-color:
#4caf50; color: white; padding:
9px 40px; border: none;
borderradius: 4px; cursor: pointer;
margin-top: 10px;
}
#[Link]
@Component({
selector: 'app-course-registration', templateUrl: './course-
[Link]', styleUrls:
['./[Link]']
}) export class
CourseRegistrationComponent {
registrationForm: FormGroup;
<app-course-registration></app-course-registration>
#[Link]
@NgModule({
declarations: [
AppComponent,
CourseRegistrationCompone nt
],
imports: [ BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
}) export class AppModule
{}
Output :
8B) Create a Book Component which fetches book details like id, name and displays
them on the page in a list format. Store the book details in an array and fetch the data
using a custom
service.
#Create a new component ng
generate component book
Program :
#in that book folder, create [Link] file
#[Link]
getBooks() {
return BOOKS;
}
}
#[Link]
<h2>My Books</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let book of books">
<td><span class="badge">{{[Link]}}</span></td>
<td>{{[Link]}}</td>
</tr>
</tbody>
</table>
#[Link]
h2 { color:
#333; }
table {
width: 20%; border- collapse:
collapse; margin- top: 20px;
}
center;
}
th { background-color:
#f2f2f2; }
.badge { display: inline-block;
padding: 0.5em 0.7em; font-
size: 75%; font-weight: bold;
line-height:
1; color: #fff; text-align:
center; white-space: nowrap;
verticalalign: baseline;
border-radius: 0.25em;
background-color: #1d1d1d;
}
#[Link]
<app-book></app-book>
Output :
Program :
#[Link]
#[Link]
data!: Observable<number>;
myArray: number[] = []; errors!:
boolean; finished!: boolean;
fetchData(): void {
[Link] = new Observable(observer => {
setTimeout(() => { [Link](11); }, 1000), setTimeout(() => {
[Link](22); }, 2000), setTimeout(() => { [Link]();
}, 3000); }); [Link]((value) => [Link](value),
EXERCISE-9:
9A)Create an application for Server Communication using HttpClient
PROGRAM:
[Link]:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [BrowserModule, HttpClientModule],
}) export class AppModule
{ } [Link]:
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse,
HttpHeaders } from '@angular/common/http'; import { Observable, throwError } from
'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { Book } from './book';
@Injectable({
providedIn:'root'
}) export class BookService { constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> { return
[Link]<Book[]>('[Link] tap((data:
any) => [Link]('Data Fetched:' + [Link](data))),
catchError([Link]));
} } [Link]: import { Injectable
} from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { catchError, tap } from 'rxjs/operators'; import {
Observable, throwError } from 'rxjs'; import {
HttpErrorResponse } from '@angular/common/http'; import {
Book } from './book';
@Injectable({
providedIn: 'root'
})
export class BookService {
private handleError(err: HttpErrorResponse): Observable<any>
{ let errMsg = ''; if ([Link] instanceof
Error) {
9B) Create a custom service called ProductService in which Http class is used to fetch
data stored in the JSON files.
PROGRAM:
[Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './[Link]'; import
{ AppComponent } from './[Link]';
import {HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
[Link]
import { Component,OnInit } from '@angular/core';
import { UserService } from './[Link]';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
title:String = 'Http Services in Angular'; users:any;
constructor(private userService:UserService){
}
ngOnInit(){
[Link]().subscribe((data)=>{
[Link]=data
})
}
}
[Link]
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService { constructor(private
http:HttpClient) {
}
getAllUsers(){
return [Link]("[Link]
}
}
[Link]
<html>
<head>
<style>
/* [Link] */
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px; /* Add some top margin for better spacing */
}
th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
tr:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<table border="2">
<tr>
<th>id</th>
<th>name</th>
<th>username</th>
<th>email</th>
</tr>
<tr *ngFor="let user of users">
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
</tr>
</table>
</body>
</html>
Output:
EXERCISE-10
10A) Create multiple components and add routing to provide navigation between
them.
[Link]:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; import {
Book } from '../book/book';
import { BookService } from '../book/[Link]';
@Component({
selector: 'app-dashboard', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class DashboardComponent implements
OnInit { books: Book[] = []; constructor( private
router: Router,
private bookService: BookService) { }
ngOnInit(): void { [Link]()
.subscribe({next:books => [Link] = [Link](1, 5)});
}
gotoDetail(book: Book): void { [Link](['/detail',
[Link]]);
}
}
[Link].htm1:
<h3>Top Books</h3>
<div class="grid grid-pad">
<div *ngFor="let book of books" (click)="gotoDetail(book)" class="col-1-4">
<div class="module book">
<h4>{{ [Link] }}</h4>
</div>
</div> </div>
[Link]:
[class*="col-"] {
float: left;
}
*,
*:after,
*:before {
-webkit-box-sizing: border-
box; -moz-box-sizing: border-
box; box-sizing: border-box; }
h3 { text-align: center; margin-
bottom: 0; } [class*="col-"] {
padding- right: 20px; padding-
bottom:
20px; }
[class*="col-"]:last-of-type
{ padding-right: 0; } .grid
{ margin: 0; } .col-1-4 {
width: 25%; } .module {
padding: 20px; text-align:
center; color: #eee; max-
height: 120px; min-width:
120px; background-color:
#607d8b; border-radius:
2px; } h4 { position:
relative; }
.module:hover {
background-color:
#eee; cursor: pointer;
color: #607d8b; } .grid-
pad { padding: 10px 0;
}
.grid-pad > [class*="col-"]:last-of-type { padding-
right: 20px;
}
@media (max-width: 600px)
{ .module { font-size:
10px; max-height: 75px;
}
}
@media (max-width: 1024px) {
.grid {
margin: 0;
}
.module { min-
width: 60px;
}
}
book-detail :
D:\MyApp>ng generate component bookDetail [Link] : import {
Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders,
HttpResponse } from '@angular/common/http'; import { Observable, throwError
} from 'rxjs';
import { catchError, tap, map} from 'rxjs/operators'; import { Book } from
'./book'; @Injectable({ providedIn:'root' }) export class BookService { booksUrl
= '[Link] private txtUrl =
'./assets/[Link]'; constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> { return [Link]<any>([Link],
{observe:'response'}).pipe( tap((data: any) => [Link]('Data
Fetched:' + [Link](data))),
catchError([Link]));
}
}
deleteBook(bookId: number):
Observable<any> { const url =
`${[Link]}/${bookId}`; return
[Link](url).pipe(
catchError([Link]));
}
private handleError(err: HttpErrorResponse):
Observable<any> {
let errMsg = ''; if ([Link] instanceof Error)
{ // A client-side or network error occurred.
Handle it accordingly.
[Link]('An error occurred:',
[Link]); errMsg =
[Link];
} else {
// The backend returned an unsuccessful response
code.
// The response body may contain clues as to
what went wrong,
[Link](`Backend returned code
${[Link]}`); errMsg
= [Link];
}
return throwError(()=>errMsg);
} } book-
[Link]:
import { Component, OnInit } from
'@angular/core';
){}
ngOnInit() {
[Link]
[Link](params
=>
{
[Link]([Link]('id')).s
ubs cribe((book) => { [Link] = book
?? [Link];
});
});
}
goBack() {
[Link]();
} } book-
[Link] : <div
*ngIf="book">
<h2>{{ [Link] }} details!</h2>
<div><label>id: </label>{{ [Link] }}</div>
<div>
<label>name: </label> <input
[(ngModel)]="[Link]" placeholder="name"
/>
</div>
<button (click)="goBack()">Back</button>
</div> book-
[Link]:
label { display:
inline-block; width:
3em; margin:
0.5em 0; color:
#607d8b; font-
weight: bold;
} input { height:
2em; font-size:
1em; padding-left:
0.4em;
} button { margin-top:
20px; font-family: Arial;
background-color: #eee;
border: none; padding:
5px 10px; border-radius:
[Link] :
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform-browser';
import { HttpClientModule } from
'@angular/common/http';
import { FormsModule } from
'@angular/forms';
import { AppComponent } from
'./[Link]';
import { BookComponent } from
'./book/[Link]';
import { DashboardComponent } from
'./dashboard/[Link]'; import
{ BookDetailComponent } from
'./bookdetail/[Link]'; import
{ AppRoutingModule } from
'./[Link]';
import { PageNotFoundComponent } from
'./page-not-found/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule,
FormsModule, AppRoutingModule], declarations:
[AppComponent, BookComponent,
DashboardComponent,
BookDetailComponent,
PageNotFoundComponent],
providers: [], bootstrap:
[AppComponent]
}) export class AppModule { }
[Link]: import { Component } from
'@angular/core';
@Component({
selector: 'app-root', styleUrls:
['./[Link]'], templateUrl:
'./[Link]'
@NgModule({
imports: [
[Link](appRoutes)
],
exports: [
RouterModule
]
})
}) export class
AppComponent { title =
'Tour of Books';
}
[Link]:
<h1>{{title}}</h1>
<nav>
color: #039be5;
background-color:
#CFD8DC; } nav [Link] {
color: #039be5; }
/* everywhere else */
*{
font-family: Arial, Helvetica, sans-serif;
} [Link]:
/* You can add global styles to this file, and
also import other style files */
body{
padding:10px; }
[Link]
:
import { Component, OnInit } from
'@angular/core'; import { Book } from './book';
import { BookService } from './[Link]';
@Component({
selector: 'app-book', templateUrl:
'./[Link]', styleUrls:
['./[Link]']
})
export class BookComponent implements
OnInit {
books!: Book[];
errorMessage!: string;
constructor(private bookService:
BookService) { } getBooks() {
[Link]().subscribe({
next: books => [Link] = books, error:error
=> [Link] =
<any>error
})
}
ngOnInit(): void {
[Link]();
}
}
[Link]:
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{ [Link] }}</span>
{{ [Link] }}
</li>
</ul>
10B) Consider the same example used for routing. Add route guard to
BooksComponent. Only after logging in, the user should be able to access
BooksComponent. If the user tries to give the URL of Bookscomponent in another tab
or window, or if the user tries to reload the BooksComponent page, it should be
redirected to LoginComponent.
Program:
[Link]
password: [],
});
}
onFormSubmit(): void { const uname =
[Link]; const pwd
= [Link];
[Link]
.isUserAuthenticated(uname, pwd)
.subscribe({next:(authenticated) => { if
(authenticated) {
[Link](['/books']);
} else {
[Link] = 'Invalid Credentials. Try again.';
}
}});
} } [Link]:
export class User
{
constructor(public userId: number, public username: string, public password: string) {
}
} [Link] : import { Injectable }
from '@angular/core'; import {
Observable, of } from 'rxjs'; import { map
} from 'rxjs/operators';
import { User } from './user';
const USERS = [
new User(1, 'user1', 'user1'),
new User(2, 'user2', 'user2')
];
const usersObservable = of(USERS); @Injectable({
providedIn: 'root'
})
export class LoginService { private
isloggedIn = false; getAllUsers():
Observable<User[]> {
return usersObservable;
}
isUserAuthenticated(username: string, password: string):
Observable<boolean> { return [Link]().pipe( map(users
=> {
const Authenticateduser = [Link](user => ([Link] === username)
&&
([Link] === password));
if (Authenticateduser)
{ [Link] = true;
} else {
[Link] = false;
}
return [Link];
);
}
isUserLoggedIn(): boolean {
return [Link];
}
} [Link]: import { Injectable } from
'@angular/core'; import { CanActivate, Router }
from '@angular/router'; import { LoginService }
from './[Link]';
@Injectable({
providedIn: 'root'
})
export class LoginGuardService implements CanActivate { constructor(private
loginService: LoginService, private router: Router) { }
canActivate(): boolean {
if ([Link]()) { return
true;
}
[Link](['/login']); return
false;
}
} [Link]:
import { NgModule } from '@angular/core'; import { BrowserModule } from
'@angular/platform-browser'; import { HttpClientModule } from
'@angular/common/http'; import { FormsModule, ReactiveFormsModule }
from '@angular/forms'; import { AppComponent } from './[Link]';
import { BookComponent } from './book/[Link]'; import {
DashboardComponent } from './dashboard/[Link]'; import {
BookDetailComponent } from './book-detail/[Link]'; import {
AppRoutingModule
} from './[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not-
[Link]'; import { LoginComponent } from './login/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule,
AppRoutingModule],
declarations: [AppComponent, LoginComponent, BookComponent,
DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
}) export class AppModule { } [Link]: import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router'; import
{ BookComponent } from './book/[Link]'; import { DashboardComponent
Program: [Link]:
import { NgModule } from '@angular/core'; import {
RouterModule, Routes } from '@angular/router'; import {
BookComponent } from './[Link]'; import {
LoginGuardService } from '../login/[Link]'; const
bookRoutes: Routes = [
{
path: '',
component: BookComponent,
canActivate: [LoginGuardService]
}
];
@NgModule({
imports: [[Link](bookRoutes)],
exports: [RouterModule]
}) export class BookRoutingModule { }
[Link] : import { NgModule } from
'@angular/core'; import { CommonModule } from
'@angular/common'; import { BookComponent } from
'./[Link]';
import { BookRoutingModule } from './[Link]';
@NgModule({
imports: [CommonModule, BookRoutingModule],
declarations: [BookComponent]
})
export class BookModule { } app- [Link]
:
import { NgModule } from '@angular/core'; import {
RouterModule, Routes } from '@angular/router';
import { BookDetailComponent } from './book-detail/[Link]'; import {
BookComponent } from './book/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ LoginGuardService } from './login/[Link]';
import { LoginComponent } from './login/[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not- [Link]';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'books', loadChildren: () => import('./book/[Link]').then(m =>
[Link]) },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent } ,
];
@NgModule({
imports: [
[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
[Link]:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http'; import
{ FormsModule, ReactiveFormsModule } from
'@angular/forms'; import { AppComponent } from
'./[Link]';
import { BookComponent } from './book/[Link]'; import {
DashboardComponent } from './dashboard/[Link]'; import {
BookDetailComponent } from './book- detail/[Link]'; import {
AppRoutingModule } from './[Link]';
import { PageNotFoundComponent } from './page-not-found/page- [Link]';
import { LoginComponent } from './login/[Link]';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule,
AppRoutingModule],
declarations: [AppComponent, LoginComponent,
DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
providers: [], bootstrap: [AppComponent]
})
export class AppModule { }
Output:
If lazy loading is not added to the demo, it has loaded in 1.14 s. Observe the load time at the
bottom of the browser console. Press F12 in the browser and click the Network tab and check
the Load time
If lazy loading is added to the demo, it has loaded in 900 ms. As BookComponent will be
loaded after login, the load time is reduced initially.
Program:
[Link]:
bookRoutes: Routes = [
path: '',
component: BookComponent,
children: [
],
canActivate: [LoginGuardService]
}];
@NgModule({
imports: [[Link](bookRoutes)],
exports: [RouterModule]
{ } [Link] :
DashboardComponent]
{ } [Link] :
<br/>
<h2>MyBooks</h2>
<ul class="books">
</li></ul>
<div><router-outlet></router-outlet></div>
<div class="error" *ngIf="errorMessage">{{errorMessage}}</div>
[Link] :
<h1>{{title}}</h1>
<nav>
</nav>
<router-outlet></router-outlet> app-
[Link]:
appRoutes: Routes = [
];
export class AppRoutingModule { }
[Link]:
ReactiveFormsModule
'./login/[Link]';
@NgModule({
[AppComponent]
{ } [Link]:
[Link](['/books/detail', [Link]]);
[Link]:
<h3>Top Books</h3>
</div>
</div> </div>
[Link]:
from '../book/[Link]';
@Component({
'./[Link]', styleUrls:
['./[Link]']
[Link]()
[Link](['/books/detail', [Link]]); }
OUTPUT
Exercise-11
11. a) Installing MongoDB on the local computer, Create MongoDB Atlas Cluster
INSTALLIING MONGODB:
1. Download MongoDB:
> For windows , run the installer and follows the prompts.
Setting Up MongoDB Atlas:
1. create an Account: Go to the MongoDB website and create an account if you haven‟t
already: MongoDB Atlas
2. create a Cluster: > Once logged in, click on “‟Clusters” and then “Create a Cluster”. >
Choose your prefered cloud provider, cluster tier, and other settings. You can often start with
the free tier for testing purposes. > Follow the prompts to set up your cluster
3. whitelist IP Adress (if necessary): Under “Security” > “Network Access”, add your IP
address to the whitelist to allow access to the cluster.
4. Connect to Your Cluster: Once your cluster is set up, click on “Connect” and follow the
instructions to connect to your cluster using MongoDB Compass or via connection strings
for your application.
Writing Code to Interact with MongoDB:
1. INSTALL the „mongodb‟ Package:
await [Link]();
}
}
run().catch([Link]) ;
11b) Write MongoDB queries to perform CRUD operations on document using insert(),
find(), update(), remove()
Program:
const express=require('express') const
app=express() const
mongoose=require('mongoose') const
bodyparser=require('body-parser') const
fs = require('fs');
const https = require('https');
[Link]([Link]())
let b=[Link]('mongodb://[Link]:27017/cserocks')
const cses3 = new [Link]({
_id:{
type:Number,
required:true
},
name:{
type:String,
required:true
}
}, {
collection:"acoerocks",
versionKey:false
}
)
const post=[Link]("acoerocks",cses3)
[Link]('/ret',(req,res)=>{
[Link]().then((data)=>{[Link](data)})
})
[Link]('/',async
(req,res)=>{ var data={
_id:[Link]._id,
name:[Link]
}
const m=new post(data)
[Link]().then((info)=>{[Link](info)})
})
[Link]('/pin/:id',async (req,res)=>{
[Link]({_id:[Link]}).then((data)=>{
[Link](data)
}) })
[Link]('/update/:id',async (req,res)=>{
var data={
name:[Link]
}
var n=[Link]
[Link](n,data).then(()=>{
[Link]("UPDATED SUCEFULLLFUL")
})
})
[Link]('/delete/:id',async (req,res)=>{ var n=[Link]
[Link](n).then(()=>{
[Link]("deleted SUCEFULLLFUL")
})
})
var server=[Link](1000, function () {
[Link]('Server running on HTTP');
var n=[Link]
[Link](n,data).then(()=>{
[Link]("UPDATED SUCEFULLLFUL")
})
})
[Link]('/delete/:id',async (req,res)=>{
var n=[Link]
[Link](n).then(()=>{
[Link]("deleted SUCEFULLLFUL")
})
})
var server=[Link](1000, function () {
[Link]('Server running on HTTP');
});
Output:
Get: [Link]
Put: [Link]
Delete: [Link]
EXPERIMENT-12:
12a) Write MongoDB queries to Create and drop databases and collections.
Program:
Here 'use' is the command for creating a new database in MongoDB and 'my_project_db' is
the name of the database. This will prompt you with a message that it has switched to a new
DB (database) name 'my_project_db'.
View the List of Databases in MongoDB:
Shows dbs
Example:
[Link]({“name”:”fruits:apples”})
Now, when you again use the show dbs command, it will now show your created database name in
the list.
12b) Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(),
aggregate().
npm install mongodb
Program:
const { MongoClient } = require('mongodb');
// Connect to MongoDB
[Link](uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(async (client) => {
[Link]('Connected to MongoDB');
const db = [Link]();
This query will return documents sorted by age in ascending order. CreateIndex():
The createIndex() method is used to create indexes to improve query performance.
// Creating an index on the "name" field [Link]({
name: 1 });
This querywill create an index on the "name" field in the "users" collection. Aggregate():
The aggregate() method is used for data aggregation operations.
// Aggregating and counting users by age [Link]([
{ $group: { _id: "$age", count: { $sum: 1 } } },
{ $sort: { _id: 1 } }
]);
This query will count the number of users for each age and sort the results by age.
OUTPUT:
Assuming a sample "users" collection: [
{ "_id": 1, "name": "Alice", "age": 30 },
{ "_id": 2, "name": "Bob", "age": 25 },
{ "_id": 3, "name": "Charlie", "age": 30 },
{ "_id": 4, "name": "David", "age": 28 },
{ "_id": 5, "name": "Eve", "age": 25 }
]
[
{ "_id": 25, "count": 2 },
{ "_id": 28, "count": 1 },