Mean Stack Lab Record
Mean Stack Lab Record
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:
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:
@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:
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.
@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>
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
In login.component.ts, define the logic for handling the form submission and credential checking.
login() {
} else {
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>
</div>
<div>
<label for="password">Password:</label>
</div>
<button type="submit">Login</button>
</form>
</div>
Ensure that FormsModule is imported in your app.module.ts file to use two-way data binding with
ngModel:
imports: [
BrowserModule,
],
Include the login component in your app.component.html or any other template where you want to
use it:
<app-login></app-login>
ng serve
6
Output:
7
b) Create a courses array and rendering it in the template using ngFor directive in a list format
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:
courses = [
];
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>
</ul>
8
Output:
9
c) Display the correct option based on the value passed to ngSwitch directive.
Define a value in your Angular component that will be used to determine which case is active.
changeOption(option: string) {
this.currentOption = option;
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>
</div>
<div *ngSwitchCase="'option2'">
<h2>Option 2 Selected</h2>
</div>
<div *ngSwitchCase="'option3'">
<h2>Option 3 Selected</h2>
</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
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:
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.
paragraphStyles = {
color: 'blue',
'font-size': '20px',
'background-color': 'lightgrey',
'padding': '10px',
};
Use the ngStyle directive in your component template to bind the styles object to the desired HTML
element.
<div>
<p [ngStyle]="paragraphStyles">
</p>
</div>
12
Output:
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;
In your Angular component, define an object or method that will return the classes you want to
apply based on certain conditions or directly.
textClasses = {
};
getTextClasses() {
return {
'text-primary': true,
'text-secondary': true,
'text-large': true,
'text-small': false
};
Apply the ngClass directive to the HTML element, binding it to the object or method defined in your
component.
<div>
<p [ngClass]="textClasses">
</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
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:
In your Angular component, define a property that holds the URL or path of the image you want to
display.
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>
</div>
16
Output:
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:
In your Angular component, define a property that will hold the value for the colspan attribute.
Use Angular’s property binding syntax to bind the colspan attribute of the <td> element to the
colspanValue property.
<table border="1">
17
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
Output:
18
Lab 5:
a) Display the product code in lowercase and product name in uppercase using built-in pipes.
1. Open src/app/hello/hello.component.ts.
2. Add properties for productCode and productName. Your class should look like this:
changeCourseName() {
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>
<h2>Product Details</h2>
19
Output:
20
b) Apply built-in pipes with parameters to display product details
1. Open src/app/hello/hello.component.ts.
2. Add properties for productPrice and releaseDate. Your class might look like this:
releaseDate: Date = new Date(2023, 8, 1); // Example release date (September 1, 2023)
changeCourseName() {
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>
<h2>Product Details</h2>
21
Output:
22
Lab 6:
a) Template Driven Forms:
Create a course registration form as a template-driven form.
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">
<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.
imports: [
BrowserModule,
],
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
<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
.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.
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:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employeeForm: FormGroup;
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.
<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:
ng new book-list
cd book-list
ng generate service_book
Update book.service.ts
@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
30
Update book.component.ts
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>
@NgModule({
declarations: [
AppComponent,
],
ng serve
31
Lab 8:
a) 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.
If you haven't already set up an Angular project, create one using Angular CLI:
ng new server-communication
cd server-communication
@NgModule({
declarations: [
AppComponent,
DataComponent // Declare your DataComponent
],
imports: [
BrowserModule,
HttpClientModule // Add HttpClientModule to imports
],
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):
32
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // API URL
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this.apiUrl);
}
}
Step 6: Update the Data Component
ngOnInit(): void {
this.dataService.getPosts().subscribe((data) => {
this.posts = data;
});
}
}
Step 7: Create the Template for Data Component
<h2>Posts</h2>
<ul>
</li>
</ul>
33
Step 8: Use the Data Component in the App Component
</div>
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:
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
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
Open src/app/product.service.ts and implement the ProductService to fetch data from the JSON file:
35
id: number;
name: string;
price: number;
}
@Injectable({
providedIn: 'root',
})
export class ProductService {
private apiUrl = 'assets/data/products.json'; // Path to the JSON file
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.apiUrl);
}
}
Step 5: Update App Module
@NgModule({
declarations: [
AppComponent,
ProductComponent // Declare your ProductComponent
],
imports: [
BrowserModule,
HttpClientModule // Add HttpClientModule to imports
],
Step 6: Generate the Product Component
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
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:
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
You can create multiple components for navigation. Let's create three components:
HomeComponent, AboutComponent, and ContactComponent.
Open src/app/app-routing.module.ts (if this file does not exist, create it) and set up the routes for
the components.
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 4: Update App Module
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:
<hr />
You can now add some basic content to each component's template.
home.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
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:
This command will create a book folder containing a book.module.ts file and update the app routing
to load it lazily.
If the BookComponent was created previously, move it into the newly created book directory (you
can also recreate it there):
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';
@NgModule({
imports: [RouterModule.forRoot(routes)],
41
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 5: Test Lazy Loading
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.
2. Select the version for your operating system (Windows, macOS, or Linux).
Windows:
4. Once installed, ensure that you have the MongoDB Server and MongoDB Compass (a
GUI for MongoDB) if you want to use it.
Mongo
2. Click on Sign Up and create an account if you don’t already have one.
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.
43
1. In the Atlas dashboard, go to the Database Access section.
3. Create a user with a username and password, and set the database user’s privileges (e.g.,
Read and Write to any database).
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.
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
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.
db.products.insertOne({
price: 29.99,
category: "Electronics"
});
db.products.insertMany([
]);
2. Read (Find)
To read documents from a collection, use the find() method. You can provide query filters to
retrieve specific documents.
db.products.find();
3. Update
db.products.updateOne(
45
{ $set: { price: 24.99 } } // Update
);
db.products.updateMany(
);
db.products.replaceOne(
{ name: "Product B" }, // Filter
{ name: "Updated Product B", price: 35.99, category: "Updated Category" } // New
document
);
4. Delete (Remove)
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")
Dropping a Collection
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()
Here’s a quick example showing how you might use these commands in the MongoDB shell:
use myNewDatabase
47
// Create a new collection
db.createCollection("myCollection")
db.myCollection.find()
db.myCollection.drop()
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
db.products.find()
2. Limiting Records
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).
db.products.find().sort({ price: 1 })
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.
5. Aggregation
The aggregate() method allows you to perform advanced data processing and analysis using the
aggregation pipeline.
49
db.products.aggregate([
])
db.products.aggregate([
])
db.products.aggregate([
{ $sort: { averagePrice: -1 } },
{ $limit: 5 }
])
db.products.find()
// Limit to 5 products
db.products.find().limit(5)
db.products.find().sort({ price: 1 })
db.products.createIndex({ name: 1 })
db.products.aggregate([
])
50
// Average price by category with sorting and limiting
db.products.aggregate([
{ $sort: { averagePrice: -1 } },
{ $limit: 5 }
])
51