R20 4-1 Mean stack
R20 4-1 Mean stack
1A)
running. Perform the below activities to understand the features of the application.
DESCRIPTION:
The AngularJS module defines the functionality of the application which is applied on the
entire HTML page. It helps to link many components. So it is just a group of related
components. It is a container that consists of different parts like controllers, services, and
directives.
Note: These modules should be made in normal HTML files like index.html and no need to
create a new project in VisualStudio for this section.
Creating a Module in AngularJS:
var app = angular.module("Module-name", []);
In this [], we can add a list of components needed but we are not including any components in
this case. This created module is bound with any tag like div, body, etc by adding it to the list
of modules.
<div ng-app = "module-name">
The code in which the module is required.
</div>
PROGRAM :
<!DOCTYPE html>
<html>
<head>
<title>
Modules and Controllers in Files
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js ">
</script>
<script src="DemoApp.js"></script>
<script src="DemoController.js"></script>
</head>
<body ng-app="DemoApp">
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AngularJS Modules</h3>
<h4>
Using controllers in Module
</h4>
<div ng-app="DemoApp"
ng-controller="DemoController">
Vowels List :
<button ng-click="ch('A')">A</button>
<button ng-click="ch('E')">E</button>
<button ng-click="ch('I')">I</button>
<button ng-click="ch('O')">O</button>
<button ng-click="ch('U')">U</button>
Vowels List :
<select ng-options="option for option in list"
ng-model="mychoice"
ng-change="c()">
</select>
</html>
OUTPUT:
1b)
AngularJS as it says is a Superheroic JavaScript MVW framework. It assists with running single-
page applications. Its goal is to augment browser-based applications with model–view–controller
(MVC) capability, in an effort to make both development and testing easier. AngularJS takes
declarative programming to whole new level. It adapts and extends traditional HTML to better
serve dynamic content through two-way data-binding that allows for the automatic
synchronization of models and views.
PROGRAM:
<!DOCTYPE html>
<html ng-app>
<head>
<title>Hello World, AngularJS - ViralPatel.net</title>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
</body>
</html>
OUTPUT:
Hello teja
1c)
Template:
Templates separate view layer from the rest of the framework so we can change the view
layer without breaking the application.
How to create template
Inline Template
We can create template inline into component class itself using template property of
@Component decorator.
PROGRAM:
@Component({
selector: 'app-hi',
template: `
`,
styleUrls: ['./hi.component.css']
})
export class HiComponent implements OnInit {
constructor() { }
ngOnInit(): void {
OUTPUT:
1.d)
Course Name: Angular JS
Module Name: Change Detection
AIM:progressively building the PoolCarz application
DESCRIPTION: Change detection is a crucial aspect of maintaining the integrity and
performance of AngularJS applications. It ensures that the user interface reflects the latest
data and that updates are efficiently propagated throughout the application. In this article,
we will explore how to detect changes in models automatically using AngularJS.
AngularJS provides a built-in mechanism for change detection through
the “$watch” function. This function allows you to monitor changes in a specific model or
expression and execute custom logic when a change is detected.
Syntax:
$scope.$watch('model', function(newValue, oldValue) {
// Custom logic to handle the change
});
PROGRAM:
<!DOCTYPE html5>
<html lang="en"
ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>
Automatic Change Detection in AngularJS
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js ">
</script>
<script>
<body ng-controller="myController">
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>
How to detect change in model automatically?
</h3>
<h4 style="color:green">{{ message }}</h4>
<input type="text" ng-model="message">
<script>
</html>
OUTPUT:
2a)
Course Name: Angular JS
Module Name: Structural Directives - ngIf
AIM: Create a login form with username and password fields. If the user enters the correct
credentials, it should render a "Welcome <>" message otherwise it should render "Invalid
Login!!! Please try again..." message
DESCRIPTION:
Syntax:
<div *ngIf="boolean"> </div>
In the above Syntax, boolean stands for either true or false value. Hence, it leads to 2 valid syntaxes as
below :
<div *ngIf="true"> </div>
<div *ngIf="false"> </div>
PROGRAM:
<div *ngIf="false">
This text will be hidden
<h1 [ngStyle]="{'color':'#FF0000'}">
GFG Structural Directive Example
</h1>
</div>
<div *ngIf="true">
This text will be displayed
<h1 [ngStyle]="{'color':'#00FF00'}">
GFG Structural Directive Example
</h1>
</div>
OUTPUT:
2b)
AIM: Create a courses array and rendering it in the template using ngFor directive in a list
format.
DESCRIPTION:
In this post, we will see how we can display the array elements in the drop-down menu
using AngularJS. Sometimes we need to display dynamically fetched data and this is where
features ngFor come into the scene. We can iterate over the array, apply conditions and
display the data
easily.
Using ngFor: NgFor is a built-in template directive that makes it easy to iterate over
something like an array or an object and create a template for each item.
Syntax:
<tag-name *ngFor="let item of array">{{iter}}</tag-name>
<tag-name *ngFor="let key of object">{{key}}</tag-name>
PROGRAM:
NgFor is a structural directive, meaning that it changes the structure of the DOM.
import { Component } from '@angular/core';
@Component({
selector: 'app-dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.css']
})
export class DropdownComponent {
players = [
"Sachin Tendulkar",
"Ricky Ponting",
"Virat Kohli",
"Kumar Sangakkara",
"Jacques Kallis",
"Hashim Amla ",
"Mahela Jayawardene ",
"Brian Lara",
"Rahul Dravid",
"AB de Villiers"
]
selected = "----"
update(e){
this.selected = e.target.value
}
}
3a)
Course Name: Angular JS
Module Name: Attribute Directives – ngStyle
AIM:Apply multiple CSS properties to a paragraph in a component using ngStyle.
PROGRAM:
component.ts file:
constructor () {
this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline';
}
getServerStatus() {
return this.serverStatus;
}
}
component.html file:
OUTPUT:
component.html file:
OUTPUT:
<!--
booleanProp, borderProp, etc...
would be properties from our
Typescript class
-->
NgClass
exportclassMyComponentClass{
myStringProperty ="is-info is-item has-border";
myArrayProperty =['is-info','is-item','has-border'];
myObjectProperty ={'is-info':true,'is-item':true};
}
<div>
<label for="one">Terms of Service</label>
<input
#oneid="one"type="checkbox"(change)="updateTos(one.checked)">
tosSign = false;
sndUsage = false;
// [ngClass]="klassStyler"
klassStyler = {
warning: false,
info: false,
error: !this.tosSign,
success: this.tosSign,
}
// ...
updateStyle() {
this.klassStyler.error = !this.tosSign;
this.klassStyler.success = this.tosSign &&this.sndUsage;
this.klassStyler.warning = this.tosSign && !this.sndUsage;
}
}
javascript
Below is the CSS:
.warning {
background: hsl(48, 100%, 67%);
border: 5px solid hsl(58, 100%, 67%);
color: black;
}
.error {
background: hsl(348, 100%, 61%);
border: 5px solid hsl(248, 100%, 61%);
color: white;
}
.success {
3c)
Course Name: Angular JS
Module Name: Custom Attribute Directive
AIM: 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:
OUTPUT
OUTPUT
Custom attribute directives - Customize theme property and default theme property
OUTPUT:
4a)
Course Name: Angular JS
Module Name: Property Binding
AIM: Binding image with class property using property binding.
PROGRAM:
Component TypeScript:
@Component({
selector: 'app-your-component',
template: `
<img [src]="imageUrl" [ngClass]="imageClass" alt="Your Image Alt Text">
`,
styles: []
})
export class YourComponent {
imageUrl: string = 'path/to/your/image.jpg';
imageClass: string = 'default-image'; // You can change this dynamically based on conditions
}
2. Explanation:
[src]="imageUrl" : This binds the src attribute of the img tag to the imageUrl
property, which should contain the path to your image.
[ngClass]="imageClass" : This binds the ngClass directive to the imageClass
property. You can change the value of imageClass dynamically based on your
conditions.
3. Usage in Parent Component:
@Component({
selector: 'app-parent',
template: `
<app-your-component></app-your-component>
`,
styles: []
})
export class ParentComponent {
// You can set properties or handle conditions here if needed
}
PROGRAM:
@Component({
selector:'app-colspan',
template:
`
<h4> Colspan Usage </h4>
<table>
<tr>
<td [attr.colspan]="colSpan">First Item </td>
</tr>
<tr>
<td>Second Item</td>
<td>Third Item </td>
</tr>
</table>
`,
styles:[`
colSpan="2"
}
OUTPUT :
4c)
Course Name: Angular JS
Module Name: Style and Event
AIM: Binding Binding an element using inline style and user actions like entering text in input fields.
PROGRAM:
Event Binding
<h1>{{firstname}}</h1>
Name: <inputtype="text" [(ngModel)]="firstname">
<button (click)="changeName()">Change Name</button>
exportclassMyApp{
firstname:string='Jimmy';
changeName(){
this.firstname='Houssein';
}
}
Style Binding
<h1 [style.color]="isHoussein() ? 'red': 'black'">{{firstname}}</h1>
Name: <inputtype="text" [(ngModel)]="firstname">
<button (click)="changeName()">Change Name</button>
exportclassMyApp{
firstname:string='Jimmy';
changeName(){
this.firstname='Houssein';
}
isHoussein(){
returnthis.firstname==='Houssein';
}
}
<h1 [ngStyle]="setStyles()">{{firstname}}</h1>
Name: <inputtype="text" [(ngModel)]="firstname">
<button (click)="changeName()">Change Name</button>
exportclassApp{
firstname:string='Jimmy';
changeName(){
this.firstname=this.alternate?'Daniel':'Houssein';
this.alternate=!this.alternate;
}
isHoussein(){
returnthis.firstname==='Houssein';
}
isDaniel(){
returnthis.firstname==='Daniel';
}
setStyles(){
letstyles={
'color':this.isHoussein()?'red':'black',
'font-size':this.isDaniel()?'3em':'2em',
'font-style':this.isDaniel()||this.isHoussein()?'italic':'normal',
};
returnstyles;
}
}
Class Binding
<h1 [class.awesome]="isHoussein()">{{firstname}}</h1>
Name: <inputtype="text" [(ngModel)]="firstname">
<button (click)="changeName()">Change Name</button>
.awesome{
color:red;
}
exportclassMyApp{
firstname:string='Jimmy';
changeName(){
this.firstname='Houssein';
}
isHoussein(){
returnthis.firstname==='Houssein';
}
}
<h1 [ngClass]="setClasses()">{{firstname}}</h1>
Name: <inputtype="text" [(ngModel)]="firstname">
<button (click)="changeName()">Change Name</button>
.italic{
font-style:italic;
}
.awesome{
color:red;
}
.move{
position:relative;
animation:move1sinfinite;
animation-duration:3s;
}
@keyframesmove{
0%{left:0px;}
50%{left:200px;}
100%{left:0px;}
}
exportclassApp{
firstname:string='Jimmy';
alternate:boolean=false;
changeName(){
this.firstname=this.alternate?'Daniel':'Houssein';
this.alternate=!this.alternate;
}
isHoussein(){
returnthis.firstname==='Houssein';
}
isDaniel(){
returnthis.firstname==='Daniel';
}
setClasses(){
letclasses={
awesome:this.isHoussein(),
move:this.isDaniel(),
italic:this.isHoussein()||this.isDaniel(),
};
returnclasses;
}
}
5a)
Course Name: Angular JS
Module Name: Built in Pipes
AIM: Display the product code in lowercase and product name in uppercase using built-in pipes.
PROGRAM:
Table of Contents
o UpperCasePipe Usage & Syntax
o UpperCasePipe Examples
o Error: InvalidPipeArgument for pipe ‘UpperCasePipe’
UpperCasePipe Examples
We go through the different types of strings and convert them to uppercase
using Angular UpperCasePipe.
id : number;
products : Product[];
constructor() {
this.id = 123;
this.products = [
{id:1,name:"product1"},
{id:2,name:"product2"}
];
}
interfaceProduct{
id: number;
name : string;
}
And now angular cli will return error TS2345: Argument of type 'number' is not assignable to
parameter of type 'string'. error when we try to execute below code.
{{ id | uppercase}}
Same with the type product
{{ products | uppercase}}
constructor(){
this.uppercasevariable = 1;
}
{{ uppercasevariable | uppercase}}
And now there will be no compile time errors and at run time we will get
following error.
5b)
Course Name: Angular JS
Module Name: Passing Parameters to Pipes
AIM: Apply built-in pipes with parameters to display product details.
PROGRAM:
5b)
Course Name: Angular JS
Module Name: Nested Components Basics
AIM: Load CourseslistComponent in the root component when a user clicks on the View courses list
button
PROGRAM:
OUTOUT:
6a)
Course Name: Angular JS
Module Name: Passing data from Container Component to Child Component
AIM: Create an AppComponent that displays a dropdown with a list of courses as values in it. Create
another component called the CoursesList component and load it in AppComponent which should
display the course details. When the user selects a course from the
PROGRAM:
...
export class CoursesListComponent {
...
course!: any[];
@Input() set cName(name: string) {
this.course = [];
for (var i = 0; i < this.courses.length; i++) {
if (this.courses[i].courseName === name) {
this.course.push(this.courses[i]);
}
}
}
}
<table border="1" *ngIf="course.length>0">
...
<tbody>
<tr *ngFor="let c of course">
<td>{{c.courseId}}</td>
<td>{{c.courseName}}</td>
</tr>
</tbody>
</table>
<h2>Course Details</h2>
Select a course to view
<select #course (change)="name = course.value">
<option value="Node JS">Node JS</option>
<option value="Typescript">Typescript</option>
<option value="Angular">Angular</option>
<option value="React JS">React JS</option></select
><br /><br />
<app-courses-list [cName]="name"></app-courses-list>
OUTPUT:
6b)
Course Name: Angular JS
Module Name: Passing data from Child Component to ContainerComponent
AIM:Create an AppComponent that loads another component called the CoursesList component.
Create another component called CoursesListComponent which should display the courses list in a
table along with a register .button in each row.
PROGRAM:
OUTPUT:
6c)
Course Name: Angular JS
Module Name: Shadow DOM
AIM: Apply ShadowDOM and None encapsulation modes to components.
PROGRAM:
ViewEncapsulation.ShadowDOM
1. Create a component called First using the following CLI command
D:\MyApp>ng generate component first
PROGRAM:
import {
Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, DoCheck,
AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy {
data = 'Angular';
ngOnInit() {
console.log('Init');
}
ngDoCheck(): void {
console.log('Change detected');
}
ngAfterContentInit(): void {
console.log('After content init');
}
ngAfterContentChecked(): void {
console.log('After content checked');
}
ngAfterViewInit(): void {
console.log('After view init');
}
ngAfterViewChecked(): void {
console.log('After view checked');
}
ngOnDestroy(): void {
console.log('Destroy');
}
}
<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]="data" />
<app-child [title]="data"></app-child>
</div>
import { Component, OnChanges, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() title!: string;
ngOnChanges(changes: any): void {
console.log('changes in child:' + JSON.stringify(changes));
}
}
<h2>Child Component</h2>
<h2>{{title}}</h2>
OUTPUT:
7a)
Course Name: Angular JS
Module Name: Template Driven Forms
AIM: Create a course registration form as a template-driven form.
PROGRAM:
export class Hero {
constructor(
public id: number,
public name: string,
public power: string,
public alterEgo?: string
){ }
}
import { Component } from '@angular/core';
@Component({
selector: 'app-hero-form',
templateUrl: './hero-form.component.html',
styleUrls: ['./hero-form.component.css']
})
export class HeroFormComponent {
submitted = false;
}
const myHero = new Hero(42, 'SkyDog',
'Fetch any object at any distance',
'Leslie Rollover');
console.log('My hero is called ' + myHero.name); // "My hero is called SkyDog"
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
OUTPUT:
7b)
Course Name: Angular JS
Module Name: Model Driven Forms or Reactive Forms
AIM: Create an employee registration form as a reactive form.
PROGRAM:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { RegistrationFormComponent } from './registration-form/registration-form.component';
@NgModule({
declarations: [
AppComponent,
RegistrationFormComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
D:\MyApp>ng generate component RegistrationForm
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.css']
})
export class RegistrationFormComponent implements OnInit {
registerForm!: FormGroup;
submitted!: boolean;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
address: this.formBuilder.group({
street: [],
zip: [],
city: []
})
});
}
}
<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" />
<p
*ngIf="(registerForm.controls.firstName.dirty ||
registerForm.controls.firstName.touched ||
registerForm.controls.firstName.pristine) &&
registerForm.controls.firstName.errors"
class="alert alert-danger">
This field is required!
</p>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName" />
<p
*ngIf="(registerForm.controls.lastName.dirty ||
registerForm.controls.lastName.touched||
registerForm.controls.lastName.pristine) &&
registerForm.controls.lastName.errors"
class="alert alert-danger">
This field is required!
</p>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<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: {{ registerForm.controls.firstName.value }}</p>
<p>Last Name: {{ registerForm.controls.lastName.value }}</p>
<p>Street: {{ registerForm.controls.address.value.street }}</p>
<p>Zip: {{ registerForm.controls.address.value.zip }}</p>
<p>City: {{ registerForm.controls.address.value.city }}</p>
</div>
</div>
.ng-valid[required] {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
<app-registration-form></app-registration-form>
OUTPUT:
7c)
Course Name: Angular JS
Module Name: Custom Validators in Reactive Forms
AIM: Create a custom validator for an email field in the employee registration form ( reactive form)
PROGRAM:
<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="registerForm.controls.firstName.errors" class="alert alert-danger">
Firstname field is invalid.
<p *ngIf="registerForm.controls.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="registerForm.controls.lastName.errors" class="alert alert-danger">
Lastname field is invaliddd.
<p *ngIf="registerForm.controls.lastName.errors?.required">
This field is required!
</p>
</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<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="registerForm.controls.email.errors" class="alert alert-danger">
Email field is invalid.
<p *ngIf="registerForm.controls.email.errors?.required">
This field is required!
</p>
<p *ngIf="registerForm.controls.email.errors?.emailInvalid">
{{ registerForm.controls.email.errors?.emailInvalid.message }}
</p>
</div>
</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: {{ registerForm.controls.firstName.value }}</p>
<p>Last Name: {{ registerForm.controls.lastName.value }}</p>
<p>Street: {{ registerForm.controls.address.value.street }}</p>
<p>Zip: {{ registerForm.controls.address.value.zip }}</p>
<p>City: {{ registerForm.controls.address.value.city }}</p>
<p>Email: {{ registerForm.controls.email.value }}</p>
</div>
</div>
OUTPUT:
8a)
Course Name: Angular JS
Module Name: Custom Validators in Template Driven forms
AIM: Create a custom validator for the email field in the course registration form.
PROGRAM:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.css']
})
export class RegistrationFormComponent implements OnInit {
registerForm!: FormGroup;
submitted!: boolean;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
address: this.formBuilder.group({
street: [],
zip: [],
city: []
}),
email: ['', [Validators.required,validateEmail]]
});
}
}
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName" />
<div *ngIf="registerForm.controls.lastName.errors" class="alert alert-danger">
Lastname field is invaliddd.
<p *ngIf="registerForm.controls.lastName.errors?.required">
This field is required!
</p>
</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<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="registerForm.controls.email.errors" class="alert alert-danger">
Email field is invalid.
<p *ngIf="registerForm.controls.email.errors?.required">
This field is required!
</p>
<p *ngIf="registerForm.controls.email.errors?.emailInvalid">
{{ registerForm.controls.email.errors?.emailInvalid.message }}
</p>
</div>
</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: {{ registerForm.controls.firstName.value }}</p>
<p>Last Name: {{ registerForm.controls.lastName.value }}</p>
<p>Street: {{ registerForm.controls.address.value.street }}</p>
<p>Zip: {{ registerForm.controls.address.value.zip }}</p>
<p>City: {{ registerForm.controls.address.value.city }}</p>
<p>Email: {{ registerForm.controls.email.value }}</p>
</div>
</div>
OTUPUT:
8b)
Course Name: Angular JS
Module Name: Services Basics
AIM: 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.
PROGRAM:
D:\MyApp>ng generate component book
export class Book {
id!: number;
name!: string;
}
import { Book } from './book';
export let BOOKS: Book[] = [
{ id: 1, name: 'HTML 5' },
{ id: 2, name: 'CSS 3' },
{ id: 3, name: 'Java Script' },
{ id: 4, name: 'Ajax Programming' },
{ id: 5, name: 'jQuery' },
{ id: 6, name: 'Mastering Node.js' },
{ id: 7, name: 'Angular JS 1.x' },
{ id: 8, name: 'ng-book 2' },
{ id: 9, name: 'Backbone JS' },
{ id: 10, name: 'Yeoman' }
];
D:\MyApp\src\app\book>ng generate service book
import { Injectable } from '@angular/core';
import { BOOKS } from './books-data';
@Injectable({
providedIn: 'root'
})
export class BookService {
getBooks() {
return BOOKS;
}
}
import { Component, OnInit } from '@angular/core';
import { Book } from './book';
import { BookService } from './book.service';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
books!: Book[];
constructor(private bookService: BookService) { }
getBooks() {
this.books = this.bookService.getBooks();
}
ngOnInit() {
this.getBooks();
}
}
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{book.id}}</span> {{book.name}}
</li>
</ul>
.books {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 13em;
}
.books li {
cursor: pointer;
position: relative;
left: 0;
background-color: #eee;
margin: 0.5em;
padding: 0.3em 0;
height: 1.5em;
border-radius: 4px;
}
.books li:hover {
color: #607d8b;
background-color: #ddd;
left: 0.1em;
}
.books .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607d8b;
line-height: 0.5em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: 0.8em;
border-radius: 4px 0 0 4px;
}
<app-book></app-book>
OUTPUT:
8c)
Course Name: Angular JS
Module Name: RxJS Observables
AIM: Create and use an observable in Angular.
PROGRAM:
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
data!: Observable<number>;
myArray: number[] = [];
errors!: boolean;
finished!: boolean;
fetchData(): void {
this.data = new Observable(observer => {
setTimeout(() => { observer.next(11); }, 1000),
setTimeout(() => { observer.next(22); }, 2000),
setTimeout(() => { observer.complete(); }, 3000);
});
this.data.subscribe((value) => this.myArray.push(value),
error => this.errors = true,
() => this.finished = true);
}
}
<b> Using Observables!</b>
<h6 style="margin-bottom: 0">VALUES:</h6>
<div *ngFor="let value of myArray">{{ value }}</div>
<div style="margin-bottom: 0">ERRORS: {{ errors }}</div>
<div style="margin-bottom: 0">FINISHED: {{ finished }}</div>
<button style="margin-top: 2rem" (click)="fetchData()">Fetch Data</button>
OUTPUT:
9a)
Course Name: Angular JS
Module Name: Server Communication using HttpClient
AIM: Create an application for Server Communication using HttpClient
PROGRAM:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {HttpClientModule} from '@angular/common/http';
import { AppComponent } from './app.component';
import { BookComponent } from './book/book.component';
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent, BookComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
OUTPUT:
9b)
Course Name: Angular JS
Module Name: Communicating with different backend services using Angular HttpClient
AIM: Create a custom service called ProductService in which Http class is used to fetch data stored in
the JSON files.
PROGRAM:
...
import { HTTP_INTERCEPTORS } from '@angular/common/http';
...
import { Interceptor1 } from './book/book.interceptor';
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent, BookComponent],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: Interceptor1,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class Interceptor1 implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Password')
});
return next.handle(authReq);
}
}
OUTPUT:
10a)
Course Name: Angular JS
Module Name: Routing Basics, Router Links
AIM: Create multiple components and add routing to provide navigation between them.
PROGRAM:
D:\MyApp>ng generate component dashboard
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Book } from '../book/book';
import { BookService } from '../book/book.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
books: Book[] = [];
constructor(
private router: Router,
private bookService: BookService) { }
ngOnInit(): void {
this.bookService.getBooks()
.subscribe({next:books =>this.books = books.slice(1, 5)});
}
gotoDetail(book: Book): void {
this.router.navigate(['/detail', book.id]);
}
}
<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>{{ book.name }}</h4>
</div>
</div>
</div>
[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;
}
}
D:\MyApp>ng generate component bookDetail
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 = 'http://localhost:3020/bookList';
private txtUrl = './assets/sample.txt';
constructor(private http: HttpClient) { }
getBooks(): Observable<Book[]> {
return this.http.get<any>(this.booksUrl, {observe:'response'}).pipe(
tap((data: any) => console.log('Data Fetched:' + JSON.stringify(data))),
catchError(this.handleError));
}
getBook(id: any) {
return this.getBooks().pipe(
map((books) =>books.find((book) => book.id == id))
);
}
addBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post('http://localhost:3020/addBook', book, { headers: options }).pipe(
catchError(this.handleError));
}
updateBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.put<any>('http://localhost:3020/update', book, { headers: options }).pipe(
tap((_: any) => console.log(`updated hero id=${book.id}`)),
catchError(this.handleError)
);
}
deleteBook(bookId: number): Observable<any> {
consturl = `${this.booksUrl}/${bookId}`;
return this.http.delete(url).pipe(
catchError(this.handleError));
}
private handleError(err: HttpErrorResponse): Observable<any> {
let errMsg = '';
if (err.errorinstanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('An error occurred:', err.error.message);
errMsg = err.error.message;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(`Backend returned code ${err.status}`);
errMsg = err.error.status;
}
return throwError(()=>errMsg);
}
}
<div *ngIf="book">
<h2>{{ book.name }} details!</h2>
<div><label>id: </label>{{ book.id }}</div>
<div>
<label>name: </label><input [(ngModel)]="book.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
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: 4px;
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #ccc;
cursor: auto;
}
D:\MyApp>ng g c PageNotFound
<div>
<h1>404 Error</h1>
<h1>Page Not Found</h1>
</div>
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
constappRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'books', component: BookComponent },
{ path: 'detail/:id', component: BookDetailComponent },
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule{ }
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 './app.component';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { AppRoutingModule } from './app-routing.module';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, FormsModule, AppRoutingModule],
declarations: [AppComponent, BookComponent, DashboardComponent, BookDetailComponent,
PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'Tour of Books';
}
<h1>{{title}}</h1>
<nav>
<a [routerLink]='["/dashboard"]' routerLinkActive="active">Dashboard</a>
<a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
</nav>
<router-outlet></router-outlet>
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
a{
cursor: pointer;
cursor: hand;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}
/* Navigation link styles */
nav a {
padding: 5px 10px;
text-decoration: none;
margin-right: 10px;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}
/* everywhere else */
*{
font-family: Arial, Helvetica, sans-serif;
}
/* You can add global styles to this file, and also import other style files */
body{
padding:10px;
}
import { Component, OnInit } from '@angular/core';
import { Book } from './book';
import { BookService } from './book.service';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
books!: Book[];
errorMessage!: string;
constructor(private bookService: BookService) { }
getBooks() {
this.bookService.getBooks().subscribe({
next: books =>this.books = books,
error:error =>this.errorMessage = <any>error
})
}
ngOnInit(): void {
this.getBooks();
}
}
<h2>My Books</h2>
<ul class="books">
<li *ngFor="let book of books">
<span class="badge">{{ book.id }}</span> {{ book.name }}
</li>
</ul>
<div class="error" *ngIf="errorMessage">{{ errorMessage }}</div>
OUTPUT:
10b)
Course Name: Angular JS
Module Name: Route Guards
AIM: Considering 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.
PROGRAM:
ng g c Login
<h3 style="position: relative; left: 60px">Login Form</h3>
<div *ngIf="invalidCredentialMsg" style="color: red">
{{ invalidCredentialMsg }}
</div>
<br />
<div style="position: relative; left: 20px">
<form [formGroup]="loginForm" (ngSubmit)="onFormSubmit()">
<p>User Name <input formControlName="username" /></p>
<p>
Password
<input
type="password"
formControlName="password"
style="position: relative; left: 10px"
/>
</p>
<p><button type="submit">Submit</button></p>
</form>
</div>
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginService } from './login.service';
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent {
invalidCredentialMsg!: string;
loginForm!:FormGroup;
constructor(
private loginService: LoginService,
private router: Router,
private formbuilder: FormBuilder
){
this.loginForm = this.formbuilder.group({
username: [],
password: [],
});
}
onFormSubmit(): void {
constuname = this.loginForm.value.username;
constpwd = this.loginForm.value.password;
this.loginService
.isUserAuthenticated(uname, pwd)
.subscribe({next:(authenticated) => {
if (authenticated) {
this.router.navigate(['/books']);
} else {
this.invalidCredentialMsg = 'Invalid Credentials. Try again.';
}
}});
}
}
export class User {
constructor(public userId: number, public username: string, public password: string) { }
}
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')
];
constusersObservable = of(USERS);
@Injectable({
providedIn: 'root'
})
export class LoginService {
private isloggedIn = false;
getAllUsers(): Observable<User[]> {
return usersObservable;
}
isUserAuthenticated(username: string, password: string): Observable<boolean> {
return this.getAllUsers().pipe(
map(users => {
constAuthenticateduser = users.find(user => (user.username === username) && (user.password ===
password));
if (Authenticateduser) {
this.isloggedIn = true;
} else {
this.isloggedIn = false;
}
return this.isloggedIn;
})
);
}
isUserLoggedIn(): boolean {
return this.isloggedIn;
}
}
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { LoginService } from './login.service';
@Injectable({
providedIn: 'root'
})
export class LoginGuardService implements CanActivate {
constructor(private loginService: LoginService, private router: Router) { }
canActivate(): boolean {
if (this.loginService.isUserLoggedIn()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
...
constappRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{path: 'login',component:LoginComponent},
{ path: 'books', component: BookComponent, canActivate:[LoginGuardService] },
{ path: 'dashboard', component: DashboardComponent},
{ path: 'detail/:id', component: BookDetailComponent},
{ path: '**', component: PageNotFoundComponent },
];
...
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 './app.component';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { AppRoutingModule } from './app-routing.module';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule,
AppRoutingModule],
declarations: [AppComponent, LoginComponent, BookComponent, DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
OUTPUT:
10c)
Course Name: Angular JS
Module Name: Asynchronous Routing
AIM: 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
PROGRAM :
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book.component';
import { LoginGuardService } from '../login/login-guard.service';
constbookRoutes: Routes = [
{
path: '',
component: BookComponent,
canActivate: [LoginGuardService]
}
];
@NgModule({
imports: [RouterModule.forChild(bookRoutes)],
exports: [RouterModule]
})
export class BookRoutingModule{ }
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BookComponent } from './book.component';
import { BookRoutingModule } from './book-routing.module';
@NgModule({
imports: [CommonModule, BookRoutingModule],
declarations: [BookComponent]
})
export class BookModule{ }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginGuardService } from './login/login-guard.service';
import { LoginComponent } from './login/login.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
constappRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'books', loadChildren: () => import('./book/book.module').then(m =>m.BookModule) },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: BookDetailComponent} ,
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule{ }
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 './app.component';
import { BookComponent } from './book/book.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { BookDetailComponent } from './book-detail/book-detail.component';
import { AppRoutingModule } from './app-routing.module';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,FormsModule,
AppRoutingModule],
declarations: [AppComponent, LoginComponent, DashboardComponent, BookDetailComponent,
PageNotFoundComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
OTUPUT:
10d)
Course Name: Angular JS
Module Name: Nested Routes
AIM: Implement Child Routes to a submodule.
PROGRAM:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { LoginComponent } from './login/login.component';
@NgModule({
imports: [BrowserModule, HttpClientModule, ReactiveFormsModule, AppRoutingModule],
declarations: [AppComponent, LoginComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule{ }
this.route.paramMap.subscribe(params => {
this.bookService.getBook(params.get('id')).subscribe((book) => {
this.book = book ?? this.book;
});
});
}
goBack() {
window.history.back();
}
}
<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>{{ book.name }}</h4>
</div>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Book } from '../book/book';
import { BookService } from '../book/book.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
books: Book[] = [];
constructor(
private router: Router,
private bookService: BookService) { }
ngOnInit(): void {
this.bookService.getBooks()
.subscribe(books =>this.books = books.slice(1, 5));
}
gotoDetail(book: Book): void {
this.router.navigate(['/books/detail', book.id]);
}
}
OUTPUT:
11a)
Course Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Installing MongoDB on the local computer, Create MongoDB Atlas Cluster
AIM: Installing MongoDB on the local computer, Create MongoDB Atlas Cluster
PROGRAM:
Overview
Use this tutorial to install MongoDB 7.0 Community Edition on Windows using the default
installation wizard.
MongoDB Version
This tutorial installs MongoDB 7.0 Community Edition. To install a different version of
MongoDB Community, use the version drop-down menu in the upper-left corner of this page
to select the documentation for that version.
Installation Method
This tutorial installs MongoDB on Windows using the default MSI installation wizard. To
install MongoDB using the msiexec.exe command-line tool instead, see Install MongoDB
using msiexec.exe. The msiexec.exe tool is useful for system administrators who wish to
deploy MongoDB in an unattended fashion using automation.
Considerations
The MongoDB Shell (mongosh) is not installed with MongoDB Server. You need to follow
the mongosh installation instructions to download and install mongosh separately.
Platform Support
MongoDB 7.0 Community Edition supports the following 64-bit versions of Windows on
x86_64 architecture:
Windows 11
NOTE
MongoDB is not supported on Windows Subsystem for Linux (WSL). To run MongoDB on
Linux, use a supported Linux system.
Virtualization
Oracle offers experimental support for VirtualBox on Windows hosts where Hyper-V is
running. However, Microsoft does not support VirtualBox on Hyper-V.
Production Notes
MongoDB logs diagnostic data to assist with troubleshooting. For detailed information,
see Full Time Diagnostic Data Capture.
On Windows, to collect system data such as disk, cpu, and memory, FTDC requires
Microsoft access permissions from the following groups:
If the user running mongod and mongos is not an administrator, add them to these groups to log
FTDC data. For more information, see the Microsoft documentation here.
Procedure
Follow these steps to install MongoDB Community Edition using the MongoDB Installer
wizard. The installation process installs both the MongoDB binaries as well as the
default configuration file <install directory>\bin\mongod.cfg.
Download the MongoDB Community .msi installer from the following link:
d. Click Download.
2
a. Go to the directory where you downloaded the MongoDB installer ( .msi file). By
default, this is your Downloads directory.
b. Double-click the .msi file.
3
The wizard steps you through the installation of MongoDB and MongoDB Compass.
MongoDB Service
MongoDB
The following installs and configures MongoDB as a Windows service.
Starting in MongoDB 4.0, you can configure and start MongoDB as a Windows
service during the install, and the MongoDB service is started upon successful
installation.
or
Install mongosh
The .msi installer does not include mongosh. Follow the mongosh installation instructions to
download and install the shell separately.
For information about the available configuration options, refer to Configuration File
Options.
If you only installed the executables and did not install MongoDB as a Windows service, you
must manually start the MongoDB instance.
See Run MongoDB Community Edition from the Command Interpreter for instructions to
start a MongoDB instance.
Starting in version 4.0, you can install and configure MongoDB as a Windows
Service during installation. The MongoDB service starts upon successful installation.
Configure the MongoDB instance with the configuration file <install directory>\bin\
mongod.cfg.
If you have not already done so, follow the mongosh installation instructions to download
and install the MongoDB Shell (mongosh).
Be sure to add the path to your mongosh.exe binary to your PATH environment variable during
installation.
Insert Documents
Query Documents
Update Documents
Delete Documents
To remove the MongoDB service, first use the Services console to stop the service. Then
open a Windows command prompt/interpreter ( cmd.exe ) as an Administrator, and run the
following command:
You can run MongoDB Community Edition from the Windows command prompt/interpreter
( cmd.exe ) instead of as a service.
IMPORTANT
Create the data directory where MongoDB stores data. MongoDB's default data directory
path is the absolute path \data\db on the drive from which you start MongoDB.
cd C:\
md "\data\db"
2
If the MongoDB database server is running correctly, the Command Interpreter displays:
IMPORTANT
Depending on the Windows Defender Firewall settings on your Windows host, Windows
may display a Security Alert dialog box about blocking "some features" of C:\Program Files\
MongoDB\Server\7.0\bin\mongod.exe from communicating on networks. To remedy this issue:
To learn more about security and MongoDB, see the Security Documentation.
Connect to MongoDB.
If you have not already done so, follow the mongosh installation instructions to download
and install the MongoDB Shell (mongosh).
Be sure to add the path to your mongosh.exe binary to your PATH environment variable during
installation.
Insert Documents
Query Documents
Update Documents
Delete Documents
Additional Considerations
Localhost Binding by Default
By default, MongoDB launches with bindIp set to 127.0.0.1 , which binds to the localhost
network interface. This means that the mongod.exe can only accept connections from clients
that are running on the same machine. Remote clients will not be able to connect to
the mongod.exe , and the mongod.exe will not be able to initialize a replica set unless this value is
set to a valid network interface.
WARNING
Before you bind your instance to a publicly-accessible IP address, you must secure your
cluster from unauthorized access. For a complete list of security recommendations,
see Security Checklist. At minimum, consider enabling authentication and hardening network
infrastructure.
If you installed MongoDB with the Windows installer ( .msi ), the .msi automatically upgrades
within its release series (e.g. 4.2.1 to 4.2.2).
Upgrading a full release series (e.g. 4.0 to 4.2) requires a new installation.
If you add C:\Program Files\MongoDB\Server\7.0\bin to your System PATH you can omit the full
path to the MongoDB Server binaries. You should also add the path to mongosh if you have
not already done so.
11b)
Course Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Introduction to the CRUD Operations
AIM: Write MongoDB queries to perform CRUD operations on document using insert(), find(),
update(), remove()
PROGRAM:
Create Operations
For MongoDB CRUD, if the specified collection doesn’t exist, the create operation will
create the collection when it’s executed. Create operations in MongoDB target a single
collection, not multiple collections. Insert operations in MongoDB are atomic on a
single document level.
MongoDB provides two different create operations that you can use to insert documents into
a collection:
db.collection.insertOne()
db.collection.insertMany()
insertOne()
As the namesake, insertOne() allows you to insert one document into the collection. For this
example, we’re going to work with a collection called RecordsDB. We can insert a single
entry into our collection by calling the insertOne() method on RecordsDB. We then provide
the information we want to insert in the form of key-value pairs, establishing the schema.
db.RecordsDB.insertOne({
name: "Marsh",
age: "6 years",
species: "Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true
})
If the create operation is successful, a new document is created. The function will return an
object where “acknowledged” is “true” and “insertID” is the newly created “ObjectId.”
>db.RecordsDB.insertOne({
... name: "Marsh",
... age: "6 years",
... species: "Dog",
... ownerAddress: "380 W. Fir Ave",
... chipped: true
... })
{
"acknowledged" : true,
"insertedId" :ObjectId("5fd989674e6b9ceb8665c57d")
}
insertMany()
It’s possible to insert multiple items at one time by calling the insertMany() method on the
desired collection. In this case, we pass multiple items into our chosen collection
(RecordsDB) and separate them by commas. Within the parentheses, we use brackets to
indicate that we are passing in a list of multiple entries. This is commonly referred to as a
nested method.
db.RecordsDB.insertMany([{
name: "Marsh",
age: "6 years",
species: "Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true},
{name: "Kitana",
age: "4 years",
species: "Cat",
ownerAddress: "521 E. Cortland",
chipped: true}])
Read Operations
The read operations allow you to supply special query filters and criteria that let you specify
which documents you want. The MongoDB documentation contains more information on the
available query filters. Query modifiers may also be used to change how many results are
returned.
db.collection.find()
db.collection.findOne()
find()
In order to get all the documents from a collection, we can simply use the find() method on
our chosen collection. Executing just the find() method with no arguments will return all
records currently in the collection.
db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat",
"ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "6 years", "species" : "Dog",
"ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "3 years", "species" : "Dog",
"ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Kevin", "age" : "8 years", "species" : "Dog",
"ownerAddress" : "900 W. Wood Way", "chipped" : true }
Here we can see that every record has an assigned “ObjectId” mapped to the “_id” key.
If you want to get more specific with a read operation and find a desired subsection of the
records, you can use the previously mentioned filtering criteria to choose what results should
be returned. One of the most common ways of filtering the results is to search by value.
db.RecordsDB.find({"species":"Cat"})
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat",
"ownerAddress" : "521 E. Cortland", "chipped" : true }
findOne()
In order to get one document that satisfies the search criteria, we can simply use
the findOne() method on our chosen collection. If multiple documents satisfy the query, this
method returns the first document according to the natural order which reflects the order of
documents on the disk. If no documents satisfy the search criteria, the function returns null.
The function takes the following form of syntax.
db.{collection}.findOne({query}, {projection})
Notice that even though two documents meet the search criteria, only the first document that
matches the search condition is returned.
Update Operations
Like create operations, update operations operate on a single collection, and they are atomic
at a single document level. An update operation takes filters and criteria to select the
documents you want to update.
You should be careful when updating documents, as updates are permanent and can’t be
rolled back. This applies to delete operations as well.
For MongoDB CRUD, there are three different methods of updating documents:
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
updateOne()
We can update a currently existing record and change a single document with an update
operation. To do this, we use the updateOne() method on a chosen collection, which here is
“RecordsDB.” To update a document, we provide the method with two arguments: an update
filter and an update action.
The update filter defines which items we want to update, and the update action defines how
to update those items. We first pass in the update filter. Then, we use the “$set” key and
provide the fields we want to update as a value. This method will update the first record that
matches the provided filter.
db.RecordsDB.updateOne({name: "Marsh"}, {$set:{ownerAddress: "451 W. Coffee St. A204"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "6 years", "species" : "Dog",
"ownerAddress" : "451 W. Coffee St. A204", "chipped" :true }
updateMany()
updateMany() allows us to update multiple items by passing in a list of items, just as we did
when inserting multiple items. This update operation uses the same syntax for updating a
single document.
db.RecordsDB.updateMany({species:"Dog"}, {$set: {age: "5"}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }
>db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat",
"ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5", "species" : "Dog",
"ownerAddress" : "451 W. Coffee St. A204", "chipped" :true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5", "species" : "Dog",
"ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Kevin", "age" : "5", "species" : "Dog",
"ownerAddress" : "900 W. Wood Way", "chipped" : true }
replaceOne()
The replaceOne() method is used to replace a single document in the specified
collection. replaceOne() replaces the entire document, meaning fields in the old document
not contained in the new will be lost.
db.RecordsDB.replaceOne({name: "Kevin"}, {name: "Maki"})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat",
"ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5", "species" : "Dog",
"ownerAddress" : "451 W. Coffee St. A204", "chipped" :true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5", "species" : "Dog",
"ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Maki" }
Delete Operations
Delete operations operate on a single collection, like update and create operations. Delete
operations are also atomic for a single document. You can provide delete operations with
filters and criteria in order to specify which documents you would like to delete from a
collection. The filter options rely on the same syntax that read operations utilize.
db.collection.deleteOne()
db.collection.deleteMany()
deleteOne()
deleteOne() is used to remove a document from a specified collection on the MongoDB
server. A filter criteria is used to specify the item to delete. It deletes the first record that
matches the provided filter.
db.RecordsDB.deleteOne({name:"Maki"})
{ "acknowledged" : true, "deletedCount" : 1 }
>db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat",
"ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5", "species" : "Dog",
"ownerAddress" : "451 W. Coffee St. A204", "chipped" :true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5", "species" : "Dog",
"ownerAddress" : "380 W. Fir Ave", "chipped" : true }
deleteMany()
deleteMany() is a method used to delete multiple documents from a desired collection with a
single delete operation. A list is passed into the method and the individual items are defined
with filter criteria as in deleteOne().
db.RecordsDB.deleteMany({species:"Dog"})
{ "acknowledged" : true, "deletedCount" : 2 }
>db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "specie
12a)
Course Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Create and Delete Databases and Collections
AIM: Write MongoDB queries to Create and drop databases and collectionS
PROGRAM:
Table of Contents
1. Prerequisites
2. Understanding MongoDB Structure
3. Creating a MongoDB Database
4. Listing Databases
5. Dropping a MongoDB Database
6. Conclusion
1. Prerequisites
Before diving into creating and dropping databases, ensure that you have MongoDB
installed on your system. You can download it from the official MongoDB website.
Additionally, it is helpful to have a basic understanding of JSON, JavaScript, and the
command line.
1. Open the MongoDB shell by running the mongo command in your terminal or
command prompt.
2. Use the use command followed by the desired database name to switch to the
new database:
1usemyNewDatabase
3. If the database does not exist, MongoDB will create it automatically. To verify
that you’ve switched to the new database, use the db command:
1db
4. To insert data into the new database, create a collection and insert a document:
1db.myCollection.insertOne({key:"value"})
5. Replace myCollection with the desired collection name and { key: “value” }
with a valid BSON document. After executing this command, MongoDB will
create the new database and collection, and store the document.
4. Listing Databases
To list all databases in your MongoDB instance, execute the show dbs command in
the MongoDB shell:
1show dbs
This command will display a list of databases along with their sizes. The newly
created database should appear in the list.
1. Open the MongoDB shell by running the mongo command in your terminal or
command prompt.
2. Use the use command followed by the target database name to switch to the
database you want to drop:
1usemyExistingDatabase
1db.dropDatabase()
4. MongoDB will delete the specified database, including all of its collections and
documents. Note that this operation is irreversible, so use caution when
executing it.
Conclusion
By mastering the process of creating, listing, and dropping databases in MongoDB,
you gain the foundational knowledge needed to manage your data effectively. As you
continue to explore MongoDB, you’ll discover its various features and capabilities,
allowing you to build powerful and scalable applications.
12b)
Course Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Introduction to MongoDB Queries
AIM: Write MongoDB queries to work with records using find(), limit(), sort(), createIndex(),
aggregate()
PROGRAM:
In MongoDB, the methods find(), limit(), sort(), createIndex(), and aggregate() are commonly used
to query and manipulate data. Here's a brief overview of each:
1.find(): The find() method is used to query a collection in MongoDB and retrieve documents
that match a specified set of criteria. It takes a query object as a parameter, and you can use
various query operators to specify conditions.
2.limit(): The limit() method is used to limit the number of documents returned by a query. It
takes an integer parameter that specifies the maximum number of documents to return.
Example:
db.collection('myCollection').find().limit(5);
3.sort(): The sort() method is used to sort the result of a query in ascending or descending
order based on one or more fields. It takes an object with field names as keys and the sort
order (1 for ascending, -1 for descending) as values.
Example:
4.createIndex() : The createIndex() method is used to create indexes on one or more fields of a
collection. Indexes improve the performance of queries by allowing MongoDB to quickly
locate the documents that match the query criteria.
Example:
db.collection('myCollection').aggregate([
{ $match: { status: 'A' } },
{ $group: { _id: '$category', total: { $sum: '$quantity' } } }
]);