Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views51 pages

Mean Stack Lab Record

Uploaded by

gnanesh847
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views51 pages

Mean Stack Lab Record

Uploaded by

gnanesh847
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Lab 1:

a) Create a new component called hello and render Hello Angular on the page
To create a new Angular component called hello and render "Hello Angular" on the page,
follow these steps

Step:1 Generate the Component: Open your terminal, navigate to your Angular project directory,
and run the Angular CLI command to generate a new component:

ng generate component hello

This command will create a new component named hello in a directory called hello with the
following files:

o hello.component.ts
o hello.component.html
o hello.component.css (or .scss depending on your style configuration)
o hello.component.spec.ts

Step:2 Update the Component Template: Open the hello.component.html file and modify it to
include the text "Hello Angular":

<p>Hello Angular</p>

Step:3 Include the Component in Your Application: Ensure the new component is declared in your
module. By default, the hello component will be automatically declared in the app.module.ts file.
Make sure it is included in the declarations array:

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


import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello/hello.component';

@NgModule({
declarations: [
AppComponent,
HelloComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

step:4 Use the Component in Your Application: To render the hello component, add its selector tag
to the main application component's template (or any other component where you want it to

1
appear). Open the app.component.html file (or another template file) and include the hello
component tag:

<app-hello></app-hello>

The selector for the hello component is defined in the hello.component.ts file. By default, it is set to
app-hello:

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


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

step:5 Run Your Application: Finally, start your Angular development server if it isn't running already:

ng serve
Open your browser and navigate to http://localhost:4200. You should see "Hello Angular" rendered
on the page where the hello component is used.

That’s it! You’ve created a new Angular component, updated its template, and rendered it in your
application.

Output:

2
b) Add an event to the hello component template and when it is clicked, it should change the
courseName.

Step1: Update the Component Class: In hello.component.ts, add a property named


courseName and a method to change it. For this example, I'll add a method called
changeCourseName.
import { Component } from '@angular/core';

@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent {
courseName: string = 'Angular Basics';

changeCourseName() {
this.courseName = 'Advanced Angular';
}
}
Stpe2: Update the Component Template: In hello.component.html, display the
courseName property and add a button that triggers the changeCourseName method when
clicked.
<p>{{ courseName }}</p>

<button (click)="changeCourseName()">Change Course Name</button>

Step3: Run Your Application: Make sure your Angular application is running. If it isn't, start it
with

ng serve

3
Output:

4
Lab 2:
a) 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..." message

Step1 : Generate the Component

Generate a new component named login:

ng generate component login

step 2: Update the Component Class

In login.component.ts, define the logic for handling the form submission and credential checking.

export class LoginComponent {

username: string = '';

password: string = '';

message: string = '';

// Dummy credentials for demonstration

private readonly correctUsername: string = 'user';

private readonly correctPassword: string = 'password';

// Method to handle form submission

login() {

if (this.username === this.correctUsername && this.password === this.correctPassword) {

this.message = `Welcome ${this.username}`;

} else {

this.message = 'Invalid Login!!! Please try again...';

Step 3. Update the Component Template

In login.component.html, create the form and bind it to the username and password properties.
Also, add a button to trigger the login method and display the message.

<div class="login-container">

<h2>Login</h2>

5
<form (ngSubmit)="login()">

<div>

<label for="username">Username:</label>

<input id="username" [(ngModel)]="username" name="username" type="text" required>

</div>

<div>

<label for="password">Password:</label>

<input id="password" [(ngModel)]="password" name="password" type="password" required>

</div>

<button type="submit">Login</button>

</form>

<p *ngIf="message">{{ message }}</p>

</div>

Step 5 Add FormsModule to Your Module

Ensure that FormsModule is imported in your app.module.ts file to use two-way data binding with
ngModel:

imports: [

BrowserModule,

FormsModule // Include FormsModule in imports

],

Step 6. Use the Component in Your Application

Include the login component in your app.component.html or any other template where you want to
use it:

<app-login></app-login>

Step 7. Run Your Application

Start your Angular application with:

ng serve

6
Output:

7
b) Create a courses array and rendering it in the template using ngFor directive in a list format

Step 1. Define Courses in Component

First, create a component or use an existing one. In the component's TypeScript file (e.g.,
app.component.ts), define an array of courses:

export class AppComponent {

courses = [

{id: 1, name: 'HTML', description: 'Hypertext markup language'},

{id:2, name: 'css', description: 'cascading stylesheet'},

{id:3, name: 'js', description: 'java script'}

];

Step 2. Render Courses in the Template

In your component's HTML file (e.g., app.component.html), use the ngFor directive to loop through
the courses array and display them in a list format:

<ul>

<li *ngFor="let course of courses">

<h3>{{ course.name }}</h3>

<p>{{ course.description }}</p>

</li>

</ul>

8
Output:

9
c) Display the correct option based on the value passed to ngSwitch directive.

Step 1: Setup the Component with a Switch Value

Define a value in your Angular component that will be used to determine which case is active.

export class SwitchExampleComponent {

currentOption: string = 'option1'; // Default option

// Method to change the option for demonstration purposes

changeOption(option: string) {

this.currentOption = option;

Step 2: Create the Template Using ngSwitch and ngSwitchCase

In the template, use the ngSwitch directive to control which content is displayed based on the
currentOption value. Each case is specified using ngSwitchCase.

<div [ngSwitch]="currentOption">

<div *ngSwitchCase="'option1'">

<h2>Option 1 Selected</h2>

<p>This is the content for Option 1.</p>

</div>

<div *ngSwitchCase="'option2'">

<h2>Option 2 Selected</h2>

<p>This is the content for Option 2.</p>

</div>

<div *ngSwitchCase="'option3'">

<h2>Option 3 Selected</h2>

<p>This is the content for Option 3.</p>

</div>

<div *ngSwitchDefault>

<h2>Default Option</h2>

10
<p>This content is displayed if no case matches.</p>

</div>

</div>

Output:

11
Lab 3:
a) Attribute Directives – ngStyle

Apply multiple CSS properties to a paragraph in a component using ngStyle

The ngStyle directive in Angular allows you to dynamically set multiple CSS properties on an
HTML element. To use ngStyle to apply multiple CSS properties to a paragraph in your component,
follow these steps:

Step 1: Define the Styles in Your Component

In your Angular component, create an object that contains the CSS properties and values you want to
apply. This object will be used with the ngStyle directive.

export class StyleExampleComponent {

// Object defining multiple CSS properties

paragraphStyles = {

color: 'blue',

'font-size': '20px',

'background-color': 'lightgrey',

'padding': '10px',

'border': '1px solid black'

};

Step 2: Apply Styles in the Component Template

Use the ngStyle directive in your component template to bind the styles object to the desired HTML
element.

<div>

<p [ngStyle]="paragraphStyles">

This paragraph has multiple CSS properties applied using ngStyle.

</p>

</div>

12
Output:

b) Module Name: ngClass

Apply multiple CSS classes to the text using ngClass directive.


The ngClass directive in Angular is used to conditionally add or remove CSS classes from an
HTML element. To apply multiple CSS classes to a text element using ngClass, you need to follow
these steps:

Step 1: Define CSS Classes in Your Stylesheet

First, define the CSS classes you want to apply in your component's stylesheet or global stylesheet.

/* src/app/style-example/style-example.component.css */

.text-primary {

color: blue;

font-weight: bold;

.text-secondary {

color: gray;

font-style: italic;

.text-large {

font-size: 24px;

.text-small {

13
font-size: 12px;

Step 2: Set Up the Component with Class Bindings

In your Angular component, define an object or method that will return the classes you want to
apply based on certain conditions or directly.

export class StyleExampleComponent {

// Define an array or object to hold the class names

textClasses = {

'text-primary': true, // Apply this class

'text-large': true, // Apply this class

'text-secondary': false // Do not apply this class

};

// Alternatively, you can use a method to return class names

getTextClasses() {

return {

'text-primary': true,

'text-secondary': true,

'text-large': true,

'text-small': false

};

Step 3: Use ngClass in the Template

Apply the ngClass directive to the HTML element, binding it to the object or method defined in your
component.

<div>

<p [ngClass]="textClasses">

This text has multiple CSS classes applied using ngClass.

</p>

14
<!-- Alternatively, using the method -->

<p [ngClass]="getTextClasses()">

This text also has multiple CSS classes applied using ngClass via method.

</p>

</div>

Output:

15
Lab 4:
a) Module Name: Property Binding

Binding image with class property using property binding.

In Angular, property binding allows you to bind the value of a property in your component to
an HTML element’s property. To bind an image source with a class property using property binding,
follow these steps:

Step 1: Define the Image Source Property in Your Component

In your Angular component, define a property that holds the URL or path of the image you want to
display.

export class ImageExampleComponent {

// Define a property for the image source

imageUrl: string = 'https://via.placeholder.com/150'; // Example URL

Step 2: Bind the Image Source to the <img> Element in the Template

In your component’s template, use property binding to bind the src attribute of the <img> element
to the imageUrl property.

<div>

<h2>Image Binding Example</h2>

<!-- Property binding to the src attribute -->

<img [src]="imageUrl" alt="Example Image">

</div>

16
Output:

b) Module Name: Attribute Binding

Binding colspan attribute of a table element to the class property.

Attribute binding in Angular allows you to bind values to attributes of HTML elements
dynamically. To bind the colspan attribute of a <td> (table data cell) element to a property in your
Angular component, follow these steps:

Step 1: Define the Property in Your Component

In your Angular component, define a property that will hold the value for the colspan attribute.

export class ColspanExampleComponent {

// Define a property for colspan

colspanValue: number = 3; // Example value for colspan

Step 2: Bind the colspan Attribute in the Template

Use Angular’s property binding syntax to bind the colspan attribute of the <td> element to the
colspanValue property.

<!-- src/app/colspan-example/colspan-example.component.html -->

<table border="1">

17
<thead>

<tr>

<th>Header 1</th>

<th>Header 2</th>

<th>Header 3</th>

</tr>

</thead>

<tbody>

<tr>

<td [attr.colspan]="colspanValue">This cell spans multiple columns.</td>

</tr>

</tbody>

</table>

Output:

18
Lab 5:
a) Display the product code in lowercase and product name in uppercase using built-in pipes.

Step 1: Update the Component Class

1. Open src/app/hello/hello.component.ts.

2. Add properties for productCode and productName. Your class should look like this:

export class HelloComponent {

courseName: string = 'Angular Basics';

productCode: string = 'PRD123';

productName: string = 'Sample Product';

changeCourseName() {

this.courseName = 'Advanced Angular';

Step 2: Update the Component Template

1. Open src/app/hello/hello.component.html.

2. Update the template to display the productCode in lowercase and the productName in
uppercase using pipes. Your HTML should look like this:

<h1>Hello Angular</h1>

<p>Current Course: {{ courseName }}</p>

<button (click)="changeCourseName()">Change Course</button>

<h2>Product Details</h2>

<p>Product Code: {{ productCode | lowercase }}</p>

<p>Product Name: {{ productName | uppercase }}</p>

19
Output:

20
b) Apply built-in pipes with parameters to display product details

Step 1: Update the Component Class

1. Open src/app/hello/hello.component.ts.

2. Add properties for productPrice and releaseDate. Your class might look like this:

export class HelloComponent {

courseName: string = 'Angular Basics';

productCode: string = 'PRD123';

productName: string = 'Sample Product';

productPrice: number = 49.99; // Example price

releaseDate: Date = new Date(2023, 8, 1); // Example release date (September 1, 2023)

changeCourseName() {

this.courseName = 'Advanced Angular';

Step 2: Update the Component Template

1. Open src/app/hello/hello.component.html.

2. Update the template to display the product details using built-in pipes with parameters. Your
HTML should look like this:

<h1>Hello Angular</h1>

<p>Current Course: {{ courseName }}</p>

<button (click)="changeCourseName()">Change Course</button>

<h2>Product Details</h2>

<p>Product Code: {{ productCode | lowercase }}</p>

<p>Product Name: {{ productName | uppercase }}</p>

<p>Product Price: {{ productPrice | currency:'USD':'symbol':'1.2-2' }}</p>

<p>Release Date: {{ releaseDate | date:'fullDate' }}</p>

21
Output:

22
Lab 6:
a) Template Driven Forms:
Create a course registration form as a template-driven form.

Creating a course registration form as a template-driven form in AngularJS involves setting up a


simple form structure using AngularJS directives. Below is a step-by-step guide on how to create this.

Step 1: Set Up Your AngularJS Application

Include AngularJS in your HTML file. Here’s a basic example of a course registration form:

<!DOCTYPE html>
<html ng-app="courseApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<style>
.error { color: red; }
</style>
<script>
// Step 2: Create AngularJS application
angular.module('courseApp', [])
.controller('CourseController', function($scope) {
$scope.courses = ['AngularJS', 'React', 'Vue.js', 'Node.js'];
$scope.registration = {};

$scope.submitForm = function() {
if ($scope.registrationForm.$valid) {
alert('Registration Successful!\n' + JSON.stringify($scope.registration));
}
};
});
</script>
</head>
<body ng-controller="CourseController">

<h2>Course Registration Form</h2>


<form name="registrationForm" ng-submit="submitForm()" novalidate>

<div>
<label for="name">Name:</label>
<input type="text" id="name" ng-model="registration.name" required />
<span class="error" ng-show="registrationForm.name.$touched &&
registrationForm.name.$invalid">Name is required.</span>
</div>

<div>
<label for="email">Email:</label>
<input type="email" id="email" ng-model="registration.email" required />
<span class="error" ng-show="registrationForm.email.$touched &&
registrationForm.email.$invalid">Valid email is required.</span>
</div>

23
<div>
<label for="course">Select Course:</label>
<select id="course" ng-model="registration.course" required>
<option value="" disabled selected>Select a course</option>
<option ng-repeat="course in courses" value="{{course}}">{{course}}</option>
</select>
<span class="error" ng-show="registrationForm.course.$touched &&
registrationForm.course.$invalid">Course selection is required.</span>
</div>

<button type="submit">Register</button>
</form>

</body>
</html>

24
b) Create an employee registration form as a reactive form.
To create an employee registration form as a reactive form in Angular, you typically use the
ReactiveFormsModule. Below is a complete example that sets up a basic employee registration form
using reactive forms.

Step 1: Modify the App Module

Open src/app/app.module.ts and import ReactiveFormsModule:

imports: [

BrowserModule,

ReactiveFormsModule // Add it here

],

Step 2: Create the Employee Registration Form

Open src/app/app.component.ts and set up the form:

export class AppComponent {


employeeForm: FormGroup;

constructor(private fb: FormBuilder) {


this.employeeForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
phone: ['', Validators.required],
position: ['', Validators.required],
});
}

onSubmit() {
if (this.employeeForm.valid) {
alert('Registration Successful!\n' + JSON.stringify(this.employeeForm.value, null, 2));
} else {
alert('Please fill out the form correctly.');
}
}
}
Step 3: Create the Template

Open src/app/app.component.html and create the form layout:


<div style="max-width: 400px; margin: auto;">
<h2>Employee Registration Form</h2>
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">

<div>
<label for="name">Name:</label>
<input id="name" formControlName="name" />

25
<div *ngIf="employeeForm.get('name').invalid && employeeForm.get('name').touched">
<small class="error">Name is required.</small>
</div>
</div>

<div>
<label for="email">Email:</label>
<input id="email" formControlName="email" />
<div *ngIf="employeeForm.get('email').invalid && employeeForm.get('email').touched">
<small class="error">Valid email is required.</small>
</div>
</div>

<div>
<label for="phone">Phone:</label>
<input id="phone" formControlName="phone" />
<div *ngIf="employeeForm.get('phone').invalid && employeeForm.get('phone').touched">
<small class="error">Phone number is required.</small>
</div>
</div>

<div>
<label for="position">Position:</label>
<input id="position" formControlName="position" />
<div *ngIf="employeeForm.get('position').invalid && employeeForm.get('position').touched">
<small class="error">Position is required.</small>
</div>
</div>

<button type="submit">Register</button>
</form>
</div>
Step 4: Add Basic Styling

You can add some basic styles to src/app/app.component.css:

.error {

color: red;

26
Output:

27
Lab 7:
a) Custom Validators in Template Driven forms

Create a custom validator for the email field in the course registration form

To create a custom validator for the email field in your Angular reactive form, you can define
a function that checks the validity of the email format. Here's how to implement a custom email
validator in the course registration form.

Step 1: Define the Custom Email Validator

You can create a custom validator function that checks whether the email meets your requirements.
For example, you can validate it against a specific pattern.

Open your app.component.ts file and add the custom validator function:

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


import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } from
'@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employeeForm: FormGroup;

constructor(private fb: FormBuilder) {


this.employeeForm = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, this.emailValidator]],
phone: ['', Validators.required],
position: ['', Validators.required],
});
}

emailValidator(control: AbstractControl): ValidationErrors | null {


const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // Adjust the pattern as
needed
const valid = emailPattern.test(control.value);
return valid ? null : { invalidEmail: true };
}

onSubmit() {
if (this.employeeForm.valid) {
alert('Registration Successful!\n' + JSON.stringify(this.employeeForm.value, null, 2));
} else {
alert('Please fill out the form correctly.');
}
}

28
}
Step 2: Update the Template

Next, update the template to display a specific error message if the email is invalid.

Open your app.component.html and modify the email input section:

<div style="max-width: 400px; margin: auto;">


<h2>Employee Registration Form</h2>
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">

<div>
<label for="name">Name:</label>
<input id="name" formControlName="name" />
<div *ngIf="employeeForm.get('name').invalid && employeeForm.get('name').touched">
<small class="error">Name is required.</small>
</div>
</div>

<div>
<label for="email">Email:</label>
<input id="email" formControlName="email" />
<div *ngIf="employeeForm.get('email').errors?.required &&
employeeForm.get('email').touched">
<small class="error">Email is required.</small>
</div>
<div *ngIf="employeeForm.get('email').errors?.invalidEmail &&
employeeForm.get('email').touched">
<small class="error">Invalid email format.</small>
</div>
</div>

<div>
<label for="phone">Phone:</label>
<input id="phone" formControlName="phone" />
<div *ngIf="employeeForm.get('phone').invalid && employeeForm.get('phone').touched">
<small class="error">Phone number is required.</small>
</div>
</div>

<div>
<label for="position">Position:</label>
<input id="position" formControlName="position" />
<div *ngIf="employeeForm.get('position').invalid && employeeForm.get('position').touched">
<small class="error">Position is required.</small>
</div>
</div>

<button type="submit">Register</button>
</form>
</div>

29
b) 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.

To create a Book Component in Angular that fetches book details from a custom service and displays
them in a list format, follow these steps:

Step 1: Set Up Your Angular Application

ng new book-list

cd book-list

Step 2: Create a Book Service

Generate a service to manage book data:

ng generate service_book

This command will create two files: book.service.ts and book.service.spec.ts.

Update book.service.ts

Open src/app/book.service.ts and modify it to include an array of book details:

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


import { Observable, of } from 'rxjs';

export interface Book {


id: number;
name: string;
}

@Injectable({
providedIn: 'root',
})
export class BookService {
private books: Book[] = [
{ id: 1, name: 'The Great Gatsby' },
{ id: 2, name: 'To Kill a Mockingbird' },
{ id: 3, name: '1984' },
{ id: 4, name: 'The Catcher in the Rye' },
];

constructor() {}

getBooks(): Observable<Book[]> {
return of(this.books); // Simulating an HTTP request
}
}
Step 3: Create the Book Component

Generate a new component for displaying the book details:

ng generate component book

30
Update book.component.ts

Open src/app/book/book.component.ts and update it to use the BookService:

export class BookComponent implements OnInit {


books: Book[] = [];

constructor(private bookService: BookService) {}

ngOnInit(): void {
this.bookService.getBooks().subscribe((data) => {
this.books = data;
});
}
}
Step 4: Create the Template

Open src/app/book/book.component.html and create the list format to display book details:

<h2>Book List</h2>
<ul>
<li *ngFor="let book of books">
ID: {{ book.id }} - Name: {{ book.name }}
</li>
</ul>

Step 5: Add the Book Component to App Module


Make sure to include the new BookComponent in your app module. Open src/app/app.module.ts
and verify it includes:

@NgModule({

declarations: [

AppComponent,

BookComponent // Add it to declarations

],

Step 6: Use the Book Component in the App Component

Open src/app/app.component.html and use the BookComponent:

<div style="text-align: center;">


<h1>Welcome to the Book List App</h1>
<app-book></app-book> <!-- Use the Book Component -->
</div>

Step 7: Run Your Application

Now you can run your application:

ng serve

31
Lab 8:
a) Server Communication using HttpClient

Create an application for Server Communication using HttpClient

To create an Angular application that communicates with a server using HttpClient, you'll
typically follow these steps. This example will guide you through setting up a simple application that
fetches data from a public API and displays it.

Step 1: Set Up Your Angular Application

If you haven't already set up an Angular project, create one using Angular CLI:

ng new server-communication

cd server-communication

Step 2: Install HttpClient Module

The HttpClient module is included in Angular's @angular/common/http package, which


should already be part of your Angular application. If it's not, ensure you have the necessary
packages installed.

Step 3: Update the App Module

Open src/app/app.module.ts and import the HttpClientModule:

@NgModule({
declarations: [
AppComponent,
DataComponent // Declare your DataComponent
],
imports: [
BrowserModule,
HttpClientModule // Add HttpClientModule to imports
],

Step 4: Generate a Data Component

Generate a new component that will handle data fetching:

ng generate component data

Step 5: Create a Data Service

Generate a service that will handle HTTP requests:

ng generate service data

Update data.service.ts

Open src/app/data.service.ts and set it up to fetch data from a public API, such as JSONPlaceholder
(a free fake online REST API for testing and prototyping):

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

32
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Post {


userId: number;
id: number;
title: string;
body: string;
}

@Injectable({
providedIn: 'root',
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // API URL

constructor(private http: HttpClient) {}

getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this.apiUrl);
}
}
Step 6: Update the Data Component

Open src/app/data/data.component.ts and set it up to use the DataService:

export class DataComponent implements OnInit {


posts: Post[] = [];

constructor(private dataService: DataService) {}

ngOnInit(): void {
this.dataService.getPosts().subscribe((data) => {
this.posts = data;
});
}
}
Step 7: Create the Template for Data Component

Open src/app/data/data.component.html and display the fetched posts:

<h2>Posts</h2>

<ul>

<li *ngFor="let post of posts">

<h3>{{ post.title }}</h3>

<p>{{ post.body }}</p>

</li>

</ul>

33
Step 8: Use the Data Component in the App Component

Open src/app/app.component.html and include the DataComponent:

<div style="text-align: center;">

<h1>Server Communication Example</h1>

<app-data></app-data> <!-- Use the DataComponent -->

</div>

Step 9: Run Your Application

Now you can run your application:

ng serve

34
b) Communicating with different backend services using Angular HttpClient

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

To create a custom service called ProductService in Angular that uses the HttpClient class to
fetch data from JSON files, follow these steps:

Step 1: Set Up Your Angular Application

If you haven’t already set up an Angular project, you can create one using Angular CLI:

ng new product-service-demo

cd product-service-demo

Step 2: Create JSON Data

Create a folder for your JSON data. Inside the src/assets directory, create a folder named
data and add a JSON file named products.json with sample product data. Here’s an example
structure:

src/assets/data/products.json

[
{
"id": 1,
"name": "Product A",
"price": 29.99
},
{
"id": 2,
"name": "Product B",
"price": 39.99
},
{
"id": 3,
"name": "Product C",
"price": 49.99
}
]
Step 3: Generate the ProductService

Generate a new service called ProductService:

ng generate service product

Step 4: Implement the ProductService

Open src/app/product.service.ts and implement the ProductService to fetch data from the JSON file:

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


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Product {

35
id: number;
name: string;
price: number;
}

@Injectable({
providedIn: 'root',
})
export class ProductService {
private apiUrl = 'assets/data/products.json'; // Path to the JSON file

constructor(private http: HttpClient) {}

getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.apiUrl);
}
}
Step 5: Update App Module

Open src/app/app.module.ts and ensure that HttpClientModule is imported:

@NgModule({
declarations: [
AppComponent,
ProductComponent // Declare your ProductComponent
],
imports: [
BrowserModule,
HttpClientModule // Add HttpClientModule to imports
],
Step 6: Generate the Product Component

Generate a new component called ProductComponent:

ng generate component product

Step 7: Implement the Product Component

Open src/app/product/product.component.ts and use the ProductService to fetch and display


product data:

export class ProductComponent implements OnInit {


products: Product[] = [];

constructor(private productService: ProductService) {}

ngOnInit(): void {
this.productService.getProducts().subscribe((data) => {
this.products = data;
});
}
}
Step 8: Create the Template for Product Component

36
Open src/app/product/product.component.html and create the list format to display product details:

<h2>Product List</h2>
<ul>
<li *ngFor="let product of products">
ID: {{ product.id }} - Name: {{ product.name }} - Price: \${{ product.price }}
</li>
</ul>
Step 9: Use the Product Component in the App Component

Open src/app/app.component.html and include the ProductComponent:

<div style="text-align: center;">


<h1>Product Service Example</h1>
<app-product></app-product> <!-- Use the ProductComponent -->
</div>
Step 10: Run Your Application

Now you can run your application:

ng serve

37
Lab 9:
a) Routing Basics, Router Links

Create multiple components and add routing to provide navigation between them

To create an Angular application with multiple components and add routing for navigation,
follow these steps:

Step 1: Set Up Your Angular Application

If you haven't set up an Angular project yet, you can create one using Angular CLI:

ng new multi-component-routing

cd multi-component-routing

Step 2: Generate Components

You can create multiple components for navigation. Let's create three components:
HomeComponent, AboutComponent, and ContactComponent.

ng generate component home

ng generate component about

ng generate component contact

Step 3: Set Up Routing

Open src/app/app-routing.module.ts (if this file does not exist, create it) and set up the routes for
the components.

If you don't have an app-routing.module.ts, create it as follows:

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


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [


{ path: '', component: HomeComponent }, // Default route
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 4: Update App Module

Open src/app/app.module.ts and ensure that AppRoutingModule is imported:


@NgModule({

38
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent
],
imports: [
BrowserModule,
AppRoutingModule // Add AppRoutingModule to imports
],
Step 5: Create Navigation Links

Open src/app/app.component.html and add navigation links to switch between the components:

<div style="text-align: center;">


<h1>Angular Routing Example</h1>
<nav>
<a routerLink="" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
<a routerLink="/contact" routerLinkActive="active">Contact</a>
</nav>

<hr />

<router-outlet></router-outlet> <!-- This is where routed components will be displayed -->


</div>
Step 6: Update Component Templates

You can now add some basic content to each component's template.

home.component.html

<h2>Welcome to the Home Page!</h2>


<p>This is the home page of our Angular application.</p>
about.component.html

<h2>About Us</h2>
<p>Learn more about our application.</p>
contact.component.html

<h2>Contact Us</h2>
<p>Get in touch through the contact page.</p>
Step 7: Add Basic Styles (Optional)

You can add some basic styles to src/styles.css to improve the navigation look:

nav a {
margin: 0 15px;
text-decoration: none;
}

nav a.active {
font-weight: bold;
text-decoration: underline;

39
}
Step 8: Run Your Application

Now you can run your application:

ng serve

40
b) Apply lazy loading to BookComponent. 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

To implement lazy loading for the BookComponent in your Angular application, you'll need to
create a feature module for the component and configure routing to load it lazily. Here’s how to do
that step-by-step:

Step 1: Create a Feature Module for Book

First, generate a module for the BookComponent:

ng generate module book --route book --module app.module

This command will create a book folder containing a book.module.ts file and update the app routing
to load it lazily.

Step 2: Move the Book Component to the Feature Module

If the BookComponent was created previously, move it into the newly created book directory (you
can also recreate it there):

ng generate component book/book

Step 3: Update the Book Module

Open the newly created book.module.ts file and ensure it looks like this:
@NgModule({
declarations: [BookComponent],
imports: [
CommonModule,
RouterModule.forChild([{ path: '', component: BookComponent }]) // Set up lazy loading
route
]
})
Step 4: Update the App Routing

Open your app-routing.module.ts file and ensure that the lazy loading is set up correctly. It should
look something like this:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [


{ path: '', redirectTo: '/home', pathMatch: 'full' }, // Example home route
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'book', loadChildren: () => import('./book/book.module').then(m => m.BookModule)
}, // Lazy loading the BookModule
];

@NgModule({
imports: [RouterModule.forRoot(routes)],

41
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 5: Test Lazy Loading

1. Run Your Application:

ng serve

42
Lab 10:
a) MongoDB Essentials - A Complete MongoDB Guide

Installing MongoDB on the local computer, Create MongoDB Atlas Cluster Install MongoDB and
configure ATLAS

a step-by-step guide on how to install MongoDB on your local computer and create a
MongoDB Atlas cluster.

Part 1: Installing MongoDB Locally

Step 1: Download MongoDB

1. Go to the MongoDB Download Center.

2. Select the version for your operating system (Windows, macOS, or Linux).

3. Download the installer package.

Step 2: Install MongoDB

 Windows:

1. Run the downloaded .msi file.

2. Follow the setup wizard. Choose "Complete" installation when prompted.


3. During installation, you may choose to install MongoDB as a service. This option is
recommended.

4. Once installed, ensure that you have the MongoDB Server and MongoDB Compass (a
GUI for MongoDB) if you want to use it.

Step 3: Verify Installation

Run the MongoDB shell to ensure it is installed correctly:

Mongo

Part 2: Create a MongoDB Atlas Cluster

Step 1: Sign Up for MongoDB Atlas

1. Go to the MongoDB Atlas website.

2. Click on Sign Up and create an account if you don’t already have one.

Step 2: Create a Cluster

1. After signing in, click on Build a Cluster.

2. Choose a Free Tier cluster.

3. Select your preferred cloud provider and region. The free tier usually offers limited
resources, but it's sufficient for development and testing.

4. Click Create Cluster. It may take a few minutes to provision your cluster.

Step 3: Configure Database Access

43
1. In the Atlas dashboard, go to the Database Access section.

2. Click on Add New Database User.

3. Create a user with a username and password, and set the database user’s privileges (e.g.,
Read and Write to any database).

4. Click Add User.

Step 4: Configure Network Access

1. Go to the Network Access section.

2. Click Add IP Address.

3. You can allow access from your current IP address or set it to allow access from anywhere
(0.0.0.0/0) for development purposes. Click Confirm.

Step 5: Connect to Your Cluster

1. In your Atlas dashboard, click on Connect for your cluster.

2. Choose Connect your application.

3. Copy the connection string provided. It should look something like this:

mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=t
rue&w=majority

Part 3: Using MongoDB Atlas with Your Application

a) Replace <username> and <password> in the connection string with your actual database
username and password.

b) You can use this connection string in your application code to connect to MongoDB Atlas
using libraries like Mongoose or the native MongoDB driver.

44
b) Introduction to the CRUD Operations
Write MongoDB queries to perform CRUD operations on document using insert(), find(),
update(), remove()

MongoDB queries for performing CRUD (Create, Read, Update, Delete) operations using the
MongoDB shell or similar interfaces.

1. Create (Insert)

To insert a document into a collection, you can use the insertOne() or insertMany() method.

Insert One Document:

db.products.insertOne({

name: "Product A",

price: 29.99,

category: "Electronics"

});

Insert Multiple Documents:

db.products.insertMany([

{ name: "Product B", price: 39.99, category: "Electronics" },

{ name: "Product C", price: 49.99, category: "Books" }

]);

2. Read (Find)

To read documents from a collection, use the find() method. You can provide query filters to
retrieve specific documents.

Find All Documents:

db.products.find();

Find Documents with a Filter:

db.products.find({ category: "Electronics" });

Find One Document:

db.products.findOne({ name: "Product A" });

3. Update

To update documents, use the updateOne(), updateMany(), or replaceOne() methods.

Update One Document:

db.products.updateOne(

{ name: "Product A" }, // Filter

45
{ $set: { price: 24.99 } } // Update

);

Update Multiple Documents:

db.products.updateMany(

{ category: "Books" }, // Filter

{ $set: { category: "Literature" } } // Update

);

Replace One Document:

db.products.replaceOne(
{ name: "Product B" }, // Filter
{ name: "Updated Product B", price: 35.99, category: "Updated Category" } // New
document
);
4. Delete (Remove)

To delete documents, use the deleteOne() or deleteMany() methods.

Delete One Document:

db.products.deleteOne({ name: "Product A" });

Delete Multiple Documents:

db.products.deleteMany({ category: "Literature" });

46
Lab 11:
a) Write MongoDB queries to Create and drop databases and collections.

Creating a Database
To create a new database, use the use command. If the database does not exist, MongoDB
will create it when you first store data in it.

Create a Database:

use myNewDatabase

This command switches to myNewDatabase. The database will be created when you insert data into
a collection within it.

Creating a Collection

To create a collection within a database, you can use the createCollection() method or simply insert a
document into the collection. The collection will be created automatically.

Create a Collection:

db.createCollection("myCollection")

Alternatively, you can create a collection by inserting a document:

db.myCollection.insertOne({ name: "Sample Document" })

Dropping a Collection

To drop (delete) a collection from a database, use the drop() method.

Drop a Collection:

db.myCollection.drop()

Dropping a Database

To drop (delete) an entire database, switch to the database you want to drop and then use the
dropDatabase() method.

Drop a Database:

use myNewDatabase

db.dropDatabase()

Example Usage in MongoDB Shell

Here’s a quick example showing how you might use these commands in the MongoDB shell:

// Create a new database

use myNewDatabase

47
// Create a new collection

db.createCollection("myCollection")

// Insert a document into the collection

db.myCollection.insertOne({ name: "Sample Document" })

// Verify the collection

db.myCollection.find()

// Drop the collection

db.myCollection.drop()

// Drop the database

db.dropDatabase()

48
c) Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(),
aggregate().

MongoDB queries demonstrating how to work with records using find(), limit(), sort(), createIndex(),
and aggregate().

1. Finding Records

To retrieve documents from a collection, use the find() method.

Find All Records:

db.products.find()

Find Specific Records:

db.products.find({ category: "Electronics" })

2. Limiting Records

To limit the number of documents returned, use the limit() method.

Limit to 5 Records:

db.products.find().limit(5)

3. Sorting Records

To sort records, use the sort() method. You can specify the sorting order (1 for ascending, -1 for
descending).

Sort by Price in Ascending Order:

db.products.find().sort({ price: 1 })

Sort by Name in Descending Order:

db.products.find().sort({ name: -1 })

4. Creating an Index

Creating an index can improve the performance of queries. You can create an index on one or more
fields in a collection.

Create an Index on the name Field:

db.products.createIndex({ name: 1 }) // 1 for ascending order

Create a Compound Index on category and price:

db.products.createIndex({ category: 1, price: -1 }) // category ascending, price descending

5. Aggregation

The aggregate() method allows you to perform advanced data processing and analysis using the
aggregation pipeline.

Basic Aggregation Example: Count Documents by Category:

49
db.products.aggregate([

{ $group: { _id: "$category", total: { $sum: 1 } } }

])

Aggregation Example: Average Price by Category:

db.products.aggregate([

{ $group: { _id: "$category", averagePrice: { $avg: "$price" } } }

])

Pipeline with Sorting and Limiting:

db.products.aggregate([

{ $group: { _id: "$category", total: { $sum: 1 }, averagePrice: { $avg: "$price" } } },

{ $sort: { averagePrice: -1 } },

{ $limit: 5 }

])

Example Usage in MongoDB Shell

Here’s how these operations might look in the MongoDB shell:

// Find all products

db.products.find()

// Limit to 5 products

db.products.find().limit(5)

// Sort products by price in ascending order

db.products.find().sort({ price: 1 })

// Create an index on the name field

db.products.createIndex({ name: 1 })

// Count documents by category using aggregation

db.products.aggregate([

{ $group: { _id: "$category", total: { $sum: 1 } } }

])

50
// Average price by category with sorting and limiting

db.products.aggregate([

{ $group: { _id: "$category", averagePrice: { $avg: "$price" } } },

{ $sort: { averagePrice: -1 } },

{ $limit: 5 }

])

51

You might also like