Angular - 2 Lab Manual
Angular - 2 Lab Manual
MONGODB
(Skill Oriented Course)
----------------------------------------------------------------------------------------------------
1.a Course Name: Angular JS
Module Name: Angular Application Setup
Observe the link http://localhost:4200/welcome on which the mCart application
is running. Perform the below activities to understand the features of the
application.
n the same MyApp application created earlier, create a new component called hello
using the following CLI command
1. D:\MyApp> ng generate component hello
2. This command will create a new folder with the name hello with the following
files placed inside it
Output:
Modules
Open index.html under the src folder.
1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>MyApp</title>
6. <base href="/">
7. <meta name="viewport" content="width=device-width, initial-scale=1">
8. <link rel="icon" type="image/x-icon" href="favicon.ico">
9. </head>
10.<body>
11. <app-root></app-root>
12.</body>
13.</html>
Line 11: loads the root component in the HTML page. app-root is the selector name
given to the component. This will execute the component and renders the template
inside the browser.
Open terminal in Visual Studio Code IDE by selecting View Menu -> Integrated
Terminal.
Note: If you get an error in the terminal like 'ng is not recognized', use the Node.js
command prompt to run this command.
Use the following command to change the port number if another application is
running on the default port(4200)
2. This command will create a new folder with the name hello with the following
files placed inside it
5. Open hello.component.css and add the following styles for the paragraph element
1. p {
2. color:blue;
3. font-size:20px;
4. }
Templates Basics
Example
app.component.html
app.component.ts
Line 5: templateUrl property is used to bind an external template file with the
component.
Output:
Angular runs a change detector algorithm on each component from top to bottom in
the component tree. This change detector algorithm is automatically generated at run
time which will check and update the changes at appropriate places in the component
tree.
Angular is very fast though it goes through all components from top to bottom for
every single event as it generates VM-friendly code. Due to this, Angular
can perform hundreds of thousands of checks in a few milliseconds.
10 | P a g e S . S r i d h a r M E S G
This login screen is created in the LoginComponent.
Find the files related to the LoginComponent in the login folder present inside the
app folder (src --> app --> login).
11 | P a g e S . S r i d h a r M E S G
'invalid':loginForm.controls['userName'].invalid &&
!loginForm.controls['userName'].pristine}" formControlName="userName">
12. <div
*ngIf="loginForm.controls['password'].errors &&
loginForm.controls['userName'].dirty">
13. <div
*ngIf="loginForm.controls['userName'].errors?.['required']"
style="color:red">UserName is required
14. </div>
15. </div>
16. </div>
17. </div>
18. <div class="form-group">
19.<label for="password" class="col-xs-4 control-label" style="text-
align:left">Password</label>
20. <div class="col-xs-8">
21.<input type="password" class="form-control"
[ngClass]="{'valid':loginForm.controls['password'].valid,
'invalid':loginForm.controls['password'].invalid &&
!loginForm.controls['password'].pristine}" formControlName="password">
22. <div
*ngIf="loginForm.controls['password'].errors &&
loginForm.controls['password'].dirty">
23. <div
*ngIf="loginForm.controls['password'].errors?.['required']"
style="color:red">Password is required
24. </div>
25. </div>
26. </div>
27. </div>
28.
29.<div *ngIf="!valid" class="error">Invalid Credentials...Please try
again...</div>
30.<br />
31.<div class="form-group">
12 | P a g e S . S r i d h a r M E S G
32.<span class="col-xs-4"></span>
33.<div class="col-xs-3">
34.<button (click)="onSubmit()" class="btn btn-primary"
[disabled]="!loginForm.valid">Login</button>
35.</div>
36.<span class="col-xs-5" style="top:8px">
37.<a [routerLink]="['/welcome']" style="color:#337ab7;text-decoration:
underline;">Cancel</a>
38. </span>
39. </div>
40. </form>
41. </div>
42. </div>
43. </div>
44.</div>
Line 7-41: We have created a form with two labels and two text boxes for username
and password
Note: In the code snippet (Line nos: 11-13 and 21-23), there are some additional
code for data binding and validations which will be explained in subsequent demos.
Line 35: A login button is created and the click event is bound with the onSubmit()
method. onSubmit() has the code to check the validity of the credentials.
Line 38: A hyperlink for canceling the operation and navigating back to the welcome
component
Note: In the code snippet (Line no: 38), there is an additional code for routing which
will be explained in subsequent demos.
3. LoginComponent has a model class coded in the login.ts, below is the code for it.
1. export class Login {
2. public userName: string='';
3. public password: string='';
4. }
Line 1-4: The Login class has two properties username and password to store the
values entered by the user in the Login form.
13 | P a g e S . S r i d h a r M E S G
4. Code for LoginComponent is coded in the file login.component.ts.
1. import { Component, ElementRef, OnInit, Renderer2, ViewChild } from
'@angular/core';
2. import { FormBuilder, FormGroup, Validators } from '@angular/forms';
3. import { Router } from '@angular/router';
4. import { Login } from './Login';
5. import { LoginService } from './login.service';
6.
7. @Component({
8. templateUrl: './login.component.html',
9. styleUrls: ['./login.component.css'],
10. providers: [LoginService]
11.})
12.export class LoginComponent implements OnInit {
13.
14. login = new Login();
15.
16. ...
17. onSubmit() {
18. //logic for validation
19. }
20.}
Line 4: Importing Login class from login.ts
Line 7-11: Component decorator marks the class as a component and templateUrl to
bind HTML page to Login component
Line 14: An instance of Login class is created
5. Finally, bind both the components of Welcome and Login in the root module.
6. This is done in the module file of the application i.e. app.module.ts file, it contains
the below-given code.
1. import { NgModule } from '@angular/core';
2. import { BrowserModule } from '@angular/platform-browser';
3. import { ReactiveFormsModule } from '@angular/forms';
14 | P a g e S . S r i d h a r M E S G
4. import { HttpClientModule } from '@angular/common/http';
5.
6. import { AppComponent } from './app.component';
7. import { AppRoutingModule } from './app-routing.module';
8. import { WelcomeComponent } from './welcome/welcome.component';
9. import { LoginComponent } from './login/login.component';
10.
11.@NgModule({
12. imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,
AppRoutingModule],
13. declarations: [AppComponent, WelcomeComponent, LoginComponent],
14. providers: [],
15. bootstrap: [AppComponent]
16.})
17.export class AppModule { }
Line 7-8: Import WelcomeComponent and LoginComponent classes
Line 13: Include them in the declarations property of NgModule decorator to make
them available in the entire module
15 | P a g e S . S r i d h a r M E S G
2.a Course Name: Angular JS
Module Name: Structural Directives - ngIf
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
Please use the below link to run the Demo on ngIf Structural Directive
Demo of Structural Directive
1. Open app.component.ts and write the following code:
1. import { Component } from '@angular/core';
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css'],
6. })
7. export class AppComponent {
8. isAuthenticated!: boolean;
9. submitted = false;
10. userName!: string;
11. onSubmit(name: string, password: string) {
12. this.submitted = true;
13. this.userName = name;
14. if (name === 'admin' && password === 'admin') {
15. this.isAuthenticated = true;
16. } else {
17. this.isAuthenticated = false;
18. }
19. }
20. }
2. Write the below-given code in app.component.html:
1. <div *ngIf="!submitted">
2. <form>
3. <label>User Name</label>
4. <input type="text" #username /><br /><br />
16 | P a g e S . S r i d h a r M E S G
5. <label for="password">Password</label>
6. <input type="password" name="password" #password /><br />
7. </form>
8. <button (click)="onSubmit(username.value,
password.value)">Login</button>
9. </div>
10. <div *ngIf="submitted">
11. <div *ngIf="isAuthenticated; else failureMsg">
12. <h4>Welcome {{ userName }}</h4>
13. </div>
14. <ng-template #failureMsg>
15. <h4>Invalid Login !!! Please try again...</h4>
16. </ng-template>
17. <button type="button" (click)="submitted = false">Back</button>
18. </div>
3. Add AppComponent to the bootstrap property in the root module file i.e.,
app.module.ts
1. import { BrowserModule } from '@angular/platform-browser';
2. import { NgModule } from '@angular/core';
3. import { AppComponent } from './app.component';
4. @NgModule({
5. declarations: [
6. AppComponent
7. ],
8. imports: [
9. BrowserModule
10. ],
11. providers: [],
12. bootstrap: [AppComponent]
13. })
14. export class AppModule { }
17 | P a g e S . S r i d h a r M E S G
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>MyApp</title>
6. <base href="/">
7. <meta name="viewport" content="width=device-width, initial-
scale=1">
8. <link rel="icon" type="image/x-icon" href="favicon.ico">
9. </head>
10. <body>
11. <app-root></app-root>
12. </body>
13. </html>
5. Save the files and check the output in the browser.
18 | P a g e S . S r i d h a r M E S G
2. b) Course Name: Angular JS
Module Name: ngFor Create a courses array and rendering it in the template
using ngFor directive in a list format.
app.component.html
1. <ul>
2. <li *ngFor="let course of courses; let i = index">
3. {{i}} - {{ course.name }}
4. </li>
5. </ul>
Line 2: ngFor iterates over courses array and displays the value of name property of
each course. It also stores the index of each item in a variable called i
Line 3: {{ i }} displays the index of each course and course.name displays the name
property value of each course.
Output:
4
19 | P a g e S . S r i d h a r M E S G
Problem Statement: Creating a courses array and rendering it in the template using
ngFor directive in a list format as shown below
20 | P a g e S . S r i d h a r M E S G
2.c Course Name: Angular JS
Module Name: ngSwitch
Display the correct option based on the value passed to ngSwitch directive.
Displaying the correct option based on the value passed to ngSwitch directive as
shown below:
21 | P a g e S . S r i d h a r M E S G
12.
13.<div>
14. <button (click)="nextChoice()">
15. Next Choice
16. </button>
17.</div>
3. Save the files and check the output in the browser
22 | P a g e S . S r i d h a r M E S G
2.d Course Name: Angular JS
Module Name: Custom Structural Directive
Create a custom structural directive called 'repeat' which should repeat the
element given a number of times.
Please use the below link to run the Demo on Custom Attribute Directive,
Demo on Custom Attribute Directive
1. Generate a directive called 'message' using the following command
1. D:\MyApp>ng generate directive message
23 | P a g e S . S r i d h a r M E S G
3. selector: '[appMessage]',
4. })
5. export class MessageDirective {
6. @Input('appMessage') message!: string;
7. constructor(private el: ElementRef, private renderer: Renderer2) {
8. renderer.setStyle(el.nativeElement, 'cursor', 'pointer');
9. }
10. @HostListener('click') onClick() {
11. this.el.nativeElement.innerHTML = this.message;
12. this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
13. }
14. }
15.
4. Write the below-given code in app.component.html
1. <h3>Attribute Directive</h3>
2. <p [appMessage]="myMessage">Click Here</p>
5. Add the following CSS styles to the app.component.css file
1. h3 {
2. color: #369;
3. font-family: Arial, Helvetica, sans-serif;
4. font-size: 250%;
5. }
6. p{
7. color: #ff0080;
8. font-family: Arial, Helvetica, sans-serif;
9. font-size: 150%;
10. }
6. Add the following code in app.component.ts
1. import { Component } from '@angular/core';
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
24 | P a g e S . S r i d h a r M E S G
7. export class AppComponent {
8. myMessage = 'Hello, I am from attribute directive';
9. }
10.
Output:
25 | P a g e S . S r i d h a r M E S G
3.a Course Name: Angular JS
Module Name: Attribute Directives - ngStyle
Apply multiple CSS properties to a paragraph in a component using ngStyle.
Please use the below link to run the Demo on ngStyle Attribute Directive,
Demo on ngStyle Attribute Directive
1. Write the below-given code in app.component.ts
1. import { Component } from '@angular/core';
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. colorName = 'red';
9. fontWeight = 'bold';
10. borderStyle = '1px solid black';
11. }
2. Write the below-given code in app.component.html
1. <p [ngStyle]="{
2. color:colorName,
3. 'font-weight':fontWeight,
4. borderBottom: borderStyle
5. }">
6. Demo for attribute directive ngStyle
7. </p>
Output:
26 | P a g e S . S r i d h a r M E S G
3.b Course Name: Angular JS Module Name: ngClass
Apply multiple CSS classes to the text using ngClass directive.
Problem Statement: Applying multiple CSS classes to the text using ngClass
directive. The output should be as shown below
27 | P a g e S . S r i d h a r M E S G
3.c Course Name: Angular JS
Module Name: Custom Attribute Directive
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.
generate a directive called 'message' using the following command
1. D:\MyApp>ng generate directive message
28 | P a g e S . S r i d h a r M E S G
5. export class MessageDirective {
6. @Input('appMessage') message!: string;
7. constructor(private el: ElementRef, private renderer: Renderer2) {
8. renderer.setStyle(el.nativeElement, 'cursor', 'pointer');
9. }
10. @HostListener('click') onClick() {
11. this.el.nativeElement.innerHTML = this.message;
12. this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
13. }
14. }
15.
4. Write the below-given code in app.component.html
1. <h3>Attribute Directive</h3>
2. <p [appMessage]="myMessage">Click Here</p>
5. Add the following CSS styles to the app.component.css file
1. h3 {
2. color: #369;
3. font-family: Arial, Helvetica, sans-serif;
4. font-size: 250%;
5. }
6. p{
7. color: #ff0080;
8. font-family: Arial, Helvetica, sans-serif;
9. font-size: 150%;
10. }
6. Add the following code in app.component.ts
1. import { Component } from '@angular/core';
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. myMessage = 'Hello, I am from attribute directive';
29 | P a g e S . S r i d h a r M E S G
9. }
10.
Output:
30 | P a g e S . S r i d h a r M E S G
4.a Course Name: Angular JS
Module Name: Property Binding
Binding image with class property using property binding.
1. @Component({
2. selector: 'app-root',
3. templateUrl: './app.component.html',
4. styleUrls: ['./app.component.css']
5. })
6. export class AppComponent {
7. imgUrl = 'assets/imgs/logo.png';
8. }
Create a folder named "imgs" inside src/assets and place a logo.png file inside it.
2. Write the following code in app.component.html as shown below
1. <img [src]='imgUrl'>
3. Save the files and check the output in the browser.
31 | P a g e S . S r i d h a r M E S G
1. import { Component } from '@angular/core';
2.
3. @Component({
4. selector: 'app-root',
5. templateUrl: './app.component.html',
6. styleUrls: ['./app.component.css']
7. })
8. export class AppComponent {
9. colspanValue = '2';
10.}
2. Write the below-given code in app.component.html
1. <table border=1>
2. <tr>
3. <td [attr.colspan]="colspanValue"> First </td>
4. <td>Second</td>
5. </tr>
6. <tr>
7. <td>Third</td>
8. <td>Fourth</td>
9. <td>Fifth</td>
10. </tr>
11.</table>
3. Save the files and check the output in the browser
32 | P a g e S . S r i d h a r M E S G
4.c Course Name: Angular JS
Module Name: Style and Event Binding
Binding an element using inline style and user actions like entering text in input
fields.
Style binding is used to set inline styles. Syntax starts with prefix style, followed by
a dot and the name of a CSS style property.
Syntax:
1. [style.styleproperty]
Example:
1. <button [style.color] = "isValid ? 'blue' : 'red' ">Hello</button>
Here button text color will be set to blue if the expression is true, otherwise red.
Example:
1. <button [style.font-size.px] = "isValid ? 3 : 6">Hello</button>
Here text font size will be set to 3 px if the expression isValid is true, otherwise, it
will be set to 6px.
The ngStyle directive is preferred when it is required to set multiple inline styles at
the same time.
33 | P a g e S . S r i d h a r M E S G
9. name = 'Angular';
10.}
11.
2. Write the below-given code in app.component.html
1. <input type="text" [(ngModel)]="name"> <br/>
2. <div>Hello , {{ name }}</div>
34 | P a g e S . S r i d h a r M E S G
5.a Course Name: Angular JS
Module Name: Built in Pipes
Display the product code in lowercase and product name in uppercase using built-in
pipes.
35 | P a g e S . S r i d h a r M E S G
36 | P a g e S . S r i d h a r M E S G
5.b Course Name: Angular JS
Module Name: Passing Parameters to Pipes
Apply built-in pipes with parameters to display product details
We have applied currency pipe to product price with locale setting as 'fr' i.e., French.
According to the French locale, the currency symbol will be displayed at the end of
the price as shown in the above output.
37 | P a g e S . S r i d h a r M E S G
7. <tr>
8. <th> Product Name </th>
9. <td> {{ productName | uppercase }} </td>
10. </tr>
11. <tr>
12. <th> Product Price </th>
13. <td> {{ productPrice | currency: 'INR':'symbol':'':'fr' }} </td>
14. </tr>
15. <tr>
16. <th> Purchase Date </th>
17. <td> {{ purchaseDate | date:'fullDate' | lowercase}} </td>
18. </tr>
19. <tr>
20. <th> Product Tax </th>
21. <td> {{ productTax | percent : '.2' }} </td>
22. </tr>
23. <tr>
24. <th> Product Rating </th>
25. <td>{{ productRating | number:'1.3-5'}} </td>
26. </tr>
27.</table>
3. Write the below-given code in app.module.ts
1. import { BrowserModule } from '@angular/platform-browser';
2. import { NgModule } from '@angular/core';
3. import { AppComponent } from './app.component';
4. import { registerLocaleData } from '@angular/common';
5. import localeFrench from '@angular/common/locales/fr';
6. registerLocaleData(localeFrench);
7.
8. @NgModule({
9. declarations: [
10. AppComponent
11. ],
12. imports: [
38 | P a g e S . S r i d h a r M E S G
13. BrowserModule
14. ],
15. providers: [],
16. bootstrap: [AppComponent]
17.})
18.export class AppModule { }
39 | P a g e S . S r i d h a r M E S G
5.c Course Name: Angular JS
Module Name: Nested Components Basics
Load CourseslistComponent in the root component when a user clicks on the View
courses list button.
Create a component called coursesList using the following CLI command
1. D:\MyApp>ng generate component coursesList
The above command will create a folder with name courses-list with the following
files
• courses-list.component.ts
• courses-list.component.html
• courses-list.component.css
• courses-list.component.spec.ts
40 | P a g e S . S r i d h a r M E S G
3. Write the below-given code in courses-list.component.ts
1. import { Component, OnInit } from '@angular/core';
2. @Component({
3. selector: 'app-courses-list',
4. templateUrl: './courses-list.component.html',
5. styleUrls: ['./courses-list.component.css']
6. })
7. export class CoursesListComponent {
8. courses = [
9. { courseId: 1, courseName: "Node JS" },
10. { courseId: 2, courseName: "Typescript" },
11. { courseId: 3, courseName: "Angular" },
12. { courseId: 4, courseName: "React JS" }
13. ];
14.}
4. Write the below-given code in courses-list.component.html
1. <table border="1">
2. <thead>
3. <tr>
4. <th>Course ID</th>
5. <th>Course Name</th>
6. </tr>
7. </thead>
8. <tbody>
9. <tr *ngFor="let course of courses">
10. <td>{{ course.courseId }}</td>
11. <td>{{ course.courseName }}</td>
12. </tr>
13. </tbody>
14.</table>
5. Add the following code in courses-list.component.css
1. tr{
2. text-align:center;
3. }
41 | P a g e S . S r i d h a r M E S G
6. Write the below-given code in app.component.html
1. <h2>Popular Courses</h2>
2. <button (click)="show = true">View Courses list</button><br /><br />
3. <div *ngIf="show">
4. <app-courses-list></app-courses-list>
5. </div>
7. Write the below-given code in app.component.ts
1. import { Component } from '@angular/core';
2.
3. @Component({
4. selector: 'app-root',
5. templateUrl: './app.component.html',
6. styleUrls: ['./app.component.css']
7. })
8. export class AppComponent {
9. show!: boolean;
10.}
8. Save the files and check the output in the browser
42 | P a g e S . S r i d h a r M E S G
load it in AppComponent which should display the course details. When the
user selects a course from the
Open the courses-list.component.ts file created in the example of nested components
and add the following code
1. import { Component, Input } from '@angular/core';
2. @Component({
3. selector: 'app-courses-list',
4. templateUrl: './courses-list.component.html',
5. styleUrls: ['./courses-list.component.css'],
6. })
7. export class CoursesListComponent {
8. courses = [
9. { courseId: 1, courseName: 'Node JS' },
10. { courseId: 2, courseName: 'Typescript' },
11. { courseId: 3, courseName: 'Angular' },
12. { courseId: 4, courseName: 'React JS' },
13. ];
14. course!: any[];
15. @Input() set cName(name: string) {
16. this.course = [];
17. for (var i = 0; i < this.courses.length; i++) {
18. if (this.courses[i].courseName === name) {
19. this.course.push(this.courses[i]);
20. }
21. }
22. }
23.}
43 | P a g e S . S r i d h a r M E S G
6. </tr>
7. </thead>
8. <tbody>
9. <tr *ngFor="let c of course">
10. <td>{{ c.courseId }}</td>
11. <td>{{ c.courseName }}</td>
12. </tr>
13. </tbody>
14.</table>
44 | P a g e S . S r i d h a r M E S G
45 | P a g e S . S r i d h a r M E S G
6.b Course Name: Angular JS
Module Name: Passing data from Child Component to ContainerComponent
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. When a user clicks on th
Open the courses-list.component.ts file created in the previous example and add the
following code
1. import { Component, OnInit, Input, Output, EventEmitter } from
'@angular/core';
2.
3. @Component({
4. selector: 'app-courses-list',
5. templateUrl: './courses-list.component.html',
6. styleUrls: ['./courses-list.component.css']
7. })
8. export class CoursesListComponent {
9. @Output() registerEvent = new EventEmitter<string>();
10. courses = [
11. { courseId: 1, courseName: 'Node JS' },
12. { courseId: 2, courseName: 'Typescript' },
13. { courseId: 3, courseName: 'Angular' },
14. { courseId: 4, courseName: 'React JS' }
15. ];
16. register(courseName: string) {
17. this.registerEvent.emit(courseName);
18. }
19.}
2. Open courses-list.component.html and add the following code
1. <table border="1">
2. <thead>
3. <tr>
4. <th>Course ID</th>
46 | P a g e S . S r i d h a r M E S G
5. <th>Course Name</th>
6. <th></th>
7. </tr>
8. </thead>
9. <tbody>
10. <tr *ngFor="let course of courses">
11. <td>{{ course.courseId }}</td>
12. <td>{{ course.courseName }}</td>
13. <td><button
(click)="register(course.courseName)">Register</button></td>
14. </tr>
15. </tbody>
16.</table>
3. Add the following in app.component.html
1. <h2>Courses List</h2>
2.
3. <app-courses-list (registerEvent)="courseReg($event)"></app-courses-list>
4. <br /><br />
5.
6. <div *ngIf="message">{{ message }}</div>
47 | P a g e S . S r i d h a r M E S G
48 | P a g e S . S r i d h a r M E S G
6.c Course Name: Angular JS
Module Name: Shadow DOM
Apply ShadowDOM and None encapsulation modes to components.
Shadow DOM is a web component standard by W3C. It enables encapsulation
for DOM tree and styles. Shadow DOM hides DOM logic behind other elements
and confines styles only for that component.
For example, in an Angular application, n number of components will be created and
each component will have its own set of data and CSS styles. When these are
integrated, there is a chance that the data and styles may be applied to the entire
application. Shadow DOM encapsulates data and styles for each component to not
flow through the entire application.
In the below example shown, each component is having its own styles defined and
they are confined to themselves:
49 | P a g e S . S r i d h a r M E S G
Problem Statement: Overriding component life-cycle hooks and logging the
corresponding messages to understand the flow. The output is as shown below.
51 | P a g e S . S r i d h a r M E S G
52 | P a g e S . S r i d h a r M E S G
7.a Course Name: Angular JS
Module Name: Model Driven Forms or Reactive Forms
Create a course registration form as a template-driven form.
Write the below-given code in app.module.ts
54 | P a g e S . S r i d h a r M E S G
27. <label>Street</label>
28. <input type="text" class="form-control" formControlName="street">
29. <label>Zip</label>
30. <input type="text" class="form-control" formControlName="zip">
31. <label>City</label>
32. <input type="text" class="form-control" formControlName="city">
33. </fieldset>
34. </div>
35. <button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>
36. </form>
37. <br/>
38. <div [hidden]="!submitted">
39. <h3> Employee Details </h3>
40. <p>First Name: {{ registerForm.get('firstName')?.value }} </p>
41. <p> Last Name: {{ registerForm.get('lastName')?.value }} </p>
42. <p> Street: {{ registerForm.get('address.street')?.value }}</p>
43. <p> Zip: {{ registerForm.get('address.zip')?.value }} </p>
44. <p> City: {{ registerForm.get('address.city')?.value }}</p>
45. </div>
46. </div>
5. Write the below-given code in registration-form.component.css
1. .ng-valid[required] {
2. border-left: 5px solid #42A948; /* green */
3. }
4.
5. .ng-invalid:not(form) {
6. border-left: 5px solid #a94442; /* red */
7. }
55 | P a g e S . S r i d h a r M E S G
56 | P a g e S . S r i d h a r M E S G
7.b Course Name: Angular JS
Module Name: Custom Validators in Reactive Forms
Create a custom validator for an email field in the employee registration form
(reactive form)
1. import { Component, OnInit } from '@angular/core';
2. import { FormBuilder, FormControl, FormGroup, Validators } from
'@angular/forms';
3.
4. @Component({
5. selector: 'app-registration-form',
6. templateUrl: './registration-form.component.html',
7. styleUrls: ['./registration-form.component.css']
8. })
9. export class RegistrationFormComponent implements OnInit {
10.
11. registerForm!: FormGroup;
12. submitted!:boolean;
13.
14. constructor(private formBuilder: FormBuilder) { }
15.
16. ngOnInit() {
17. this.registerForm = this.formBuilder.group({
18. firstName: ['',Validators.required],
19. lastName: ['', Validators.required],
20. address: this.formBuilder.group({
21. street: [],
22. zip: [],
23. city: []
24. }),
25. email: ['',[Validators.required,validateEmail]]
26. });
27. }
28.
29.}
30.function validateEmail(c: FormControl): any {
57 | P a g e S . S r i d h a r M E S G
31. let EMAIL_REGEXP = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-
Z]{2,5})$/;
32.
33. return EMAIL_REGEXP.test(c.value) ? null : {
34. emailInvalid: {
35. message: "Invalid Format!"
36. }
37. };
38.}
2. Add HTML controls for the email field in the registration-
form.component.html file as shown below
1. <div class="container">
2. <h1>Registration Form</h1>
3. <form [formGroup]="registerForm">
4. <div class="form-group">
5. <label>First Name</label>
6. <input type="text" class="form-control"
formControlName="firstName">
7. <div *ngIf="registerForm.controls['firstName'].errors" class="alert
alert-danger">
8. Firstname field is invalid.
9. <p *ngIf="registerForm.controls['firstName'].errors?.['required']">
10. This field is required!
11. </p>
12. </div>
13. </div>
14. <div class="form-group">
15. <label>Last Name</label>
16. <input type="text" class="form-control"
formControlName="lastName">
17. <div *ngIf="registerForm.controls['lastName'].errors" class="alert alert-
danger">
18. Lastname field is invalid.
19. <p *ngIf="registerForm.controls['lastName'].errors?.['required']">
58 | P a g e S . S r i d h a r M E S G
20. This field is required!
21. </p>
22. </div>
23. </div>
24. <div class="form-group">
25. <fieldset formGroupName="address">
26. <legend>Address:</legend>
27. <label>Street</label>
28. <input type="text" class="form-control" formControlName="street">
29. <label>Zip</label>
30. <input type="text" class="form-control" formControlName="zip">
31. <label>City</label>
32. <input type="text" class="form-control" formControlName="city">
33. </fieldset>
34. </div>
35. <div class="form-group">
36. <label>Email</label>
37. <input type="text" class="form-control" formControlName="email" />
38. <div *ngIf="registerForm.controls['email'].errors" class="alert alert-
danger">
39. Email field is invalid.
40. <p *ngIf="registerForm.controls['email'].errors?.['required']">
41. This field is required!
42. </p>
43. <p *ngIf="registerForm.controls['email'].errors?.['emailInvalid']">
44. {{ registerForm.controls['email'].errors?.['emailInvalid'].message }}
45. </p>
46. </div>
47. </div>
48. <button type="submit" class="btn btn-primary"
(click)="submitted=true">Submit</button>
49. </form>
50. <br/>
51. <div [hidden]="!submitted">
52. <h3> Employee Details </h3>
59 | P a g e S . S r i d h a r M E S G
53. <p>First Name: {{ registerForm.get('firstName')?.value }} </p>
54. <p> Last Name: {{ registerForm.get('lastName')?.value }} </p>
55. <p> Street: {{ registerForm.get('address.street')?.value }}</p>
56. <p> Zip: {{ registerForm.get('address.zip')?.value }} </p>
57. <p> City: {{ registerForm.get('address.city')?.value }}</p>
58. <p>Email: {{ registerForm.get('email')?.value }}</p>
59. </div>
60. </div>
60 | P a g e S . S r i d h a r M E S G
8.a Course Name: Angular JS
Module Name: Services Basics
Create a Book Component which fetches book details like id, name and displays
them on the page in a list format. Store the book details in an array and fetch
the data using a custom service.
Create BookComponent by using the following CLI command
1. D:\MyApp>ng generate component book
2. Create a file with the name book.ts under the book folder and add the following
code.
1. export class Book {
2. id!: number;
3. name!: string;
4. }
3. Create a file with the name books-data.ts under the book folder and add the
following code.
1. import { Book } from './book';
2. export let BOOKS: Book[] = [
3. { id: 1, name: 'HTML 5' },
4. { id: 2, name: 'CSS 3' },
5. { id: 3, name: 'Java Script' },
6. { id: 4, name: 'Ajax Programming' },
7. { id: 5, name: 'jQuery' },
8. { id: 6, name: 'Mastering Node.js' },
9. { id: 7, name: 'Angular JS 1.x' },
10. { id: 8, name: 'ng-book 2' },
11. { id: 9, name: 'Backbone JS' },
12. { id: 10, name: 'Yeoman' }
13.];
4. Create a service called BookService under the book folder using the following
CLI command
1. D:\MyApp\src\app\book>ng generate service book
5. Add the following code in book.service.ts
1. import { Injectable } from '@angular/core';
61 | P a g e S . S r i d h a r M E S G
2. import { BOOKS } from './books-data';
3.
4. @Injectable({
5. providedIn: 'root'
6. })
7.
8. export class BookService {
9. getBooks() {
10. return BOOKS;
11. }
12.}
62 | P a g e S . S r i d h a r M E S G
7. Write the below-given code in book.component.html
1. <h2>My Books</h2>
2. <ul class="books">
3. <li *ngFor="let book of books">
4. <span class="badge">{{book.id}}</span> {{book.name}}
5. </li>
6. </ul>
8. Add the following code in book.component.css which has styles for books
1. .books {
2. margin: 0 0 2em 0;
3. list-style-type: none;
4. padding: 0;
5. width: 13em;
6. }
7. .books li {
8. cursor: pointer;
9. position: relative;
10. left: 0;
11. background-color: #eee;
12. margin: 0.5em;
13. padding: 0.3em 0;
14. height: 1.5em;
15. border-radius: 4px;
16.}
17..books li:hover {
18. color: #607d8b;
19. background-color: #ddd;
20. left: 0.1em;
21.}
22..books .badge {
23. display: inline-block;
24. font-size: small;
25. color: white;
63 | P a g e S . S r i d h a r M E S G
26. padding: 0.8em 0.7em 0 0.7em;
27. background-color: #607d8b;
28. line-height: 0.5em;
29. position: relative;
30. left: -1px;
31. top: -4px;
32. height: 1.8em;
33. margin-right: 0.8em;
34. border-radius: 4px 0 0 4px;
35.}
9. Add the following code in app.component.html
1. <app-book></app-book>
10. Save the files and check the output in the browser
64 | P a g e S . S r i d h a r M E S G
8.b Course Name: Angular JS
Module Name: RxJS Observables
Create and use an observable in Angular RxJS
Reactive Extensions for JavaScript (RxJS) is a third-party library used by
the Angular team.
RxJS is a reactive streams library used to work with asynchronous streams of data.
Observables, in RxJS, are used to represent asynchronous streams of data.
Observables are a more advanced version of Promises in JavaScript
app.component.html
1. <b> Using Observables!</b>
2.
66 | P a g e S . S r i d h a r M E S G
3. <h6 style="margin-bottom: 0">VALUES:</h6>
4. <div *ngFor="let value of myArray">{{ value }}</div>
5.
6. <div style="margin-bottom: 0">ERRORS: {{ errors }}</div>
7.
8. <div style="margin-bottom: 0">FINISHED: {{ finished }}</div>
9.
10.<button style="margin-top: 2rem" (click)="fetchData()">Fetch
Data</button>
Line 4: ngFor loop is iterated on myArray which will display the values on the page
Line 6: {{ errors }} will render the value of errors property if any
Line 8: Displays finished property value when complete() method of Observable is
executed
Line 10: Button click event is bound with fetchData() method which is invoked and
creates an observable with a stream of numeric values.
Output:
67 | P a g e S . S r i d h a r M E S G
9.a Course Name: Angular JS
Module Name: Server Communication using HttpClient
Create an application for Server Communication using HttpClient
Problem Statement:
1. Fetching books data using HttpClient class.
2. Sending a request for adding a new book using HttpClient class.
3. Updating an existing book using HttpClient class.
4. Deleting a book using HttpClient class.
• In the example used for custom services concept, add HttpModule to the
app.module.ts to make use of HttpClient class.
1. import { NgModule } from '@angular/core';
2. import { BrowserModule } from '@angular/platform-browser';
3. import {HttpClientModule} from '@angular/common/http';
4. import { AppComponent } from './app.component';
5. import { BookComponent } from './book/book.component';
6. @NgModule({
7. imports: [BrowserModule, HttpClientModule],
8. declarations: [AppComponent, BookComponent],providers: [],
9. bootstrap: [AppComponent]
10. })
11.export class AppModule { }
12.
68 | P a g e S . S r i d h a r M E S G
2. import { HttpClient, HttpErrorResponse, HttpHeaders } from
'@angular/common/http';
3. import { Observable, throwError } from 'rxjs';
4. import { catchError, tap } from 'rxjs/operators';
5. import { Book } from './book';
6. @Injectable({
7. providedIn:'root'
8. })
9. export class BookService {
10. booksUrl = 'http://localhost:3020/bookList';
11. constructor(private http: HttpClient) { }
12. getBooks(): Observable<Book[]> {
13. return this.http.get<Book[]>('http://localhost:3020/bookList').pipe(
14. tap((data: any) => console.log('Data Fetched:' + JSON.stringify(data))),
15. catchError(this.handleError));
16. }
17. addBook(book: Book): Observable<any> {
18. const options = new HttpHeaders({ 'Content-Type': 'application/json' });
19. return this.http.post('http://localhost:3020/addBook', book, { headers:
options }).pipe(
20. catchError(this.handleError));
21. }
22. updateBook(book: Book): Observable<any> {
23. const options = new HttpHeaders({ 'Content-Type': 'application/json' });
24. return
this.http.put<any>('http://localhost:3020/update', book, { headers: options
}).pipe(
25. tap((_: any) => console.log(`updated hero id=${book.id}`)),
26. catchError(this.handleError)
27. );
28. }
29. deleteBook(bookId: number): Observable<any> {
30. const url = `${this.booksUrl}/${bookId}`;
31. return this.http.delete(url).pipe(
32. catchError(this.handleError));
69 | P a g e S . S r i d h a r M E S G
33. }
34. private handleError(err: HttpErrorResponse): Observable<any> {
35. let errMsg = '';
36. if (err.error instanceof Error) {
37. // A client-side or network error occurred. Handle it accordingly.
38.console.log('An error occurred:', err.error.message);
39. errMsg = err.error.message;
40. } else {
41. // The backend returned an unsuccessful response code.
42. // The response body may contain clues as to what went wrong,
43. console.log(`Backend returned code ${err.status}`);
44. errMsg = err.error.status;
45. }
46. return throwError(()=>errMsg);
47. }
48. }
49.
74 | P a g e S . S r i d h a r M E S G
75 | P a g e S . S r i d h a r M E S G
10.a Course Name: Angular JS
Module Name: Routing Basics, Router Links
Create multiple components and add routing to provide navigation between
them.
Problem Statement: Create multiple components and adding routing to provide
navigation between them. The output is as shown below
Consider the example used for the HttpClient concept.
2. Create another component with the name dashboard using the following command
1. D:\MyApp>ng generate component dashboard
83 | P a g e S . S r i d h a r M E S G
15. Write the below-given code in app.component.ts
1. import { Component } from '@angular/core';
2. @Component({
3. selector: 'app-root',
4. styleUrls: ['./app.component.css'],
5. templateUrl: './app.component.html'
6. })
7. export class AppComponent {
8. title = 'Tour of Books';
9. }
18. Open styles.css under the src folder and add the following code
1. /* You can add global styles to this file, and also import other style files */
2. body{
3. padding:10px;
4. }
19. Open book.component.ts file in book folder and add the following code
1. import { Component, OnInit } from '@angular/core';
2. import { BooksdataService } from './booksdata.service';
3. @Component({
4. selector: 'app-book',
5. templateUrl: './book.component.html',
6. styleUrls: ['./book.component.css']
7. })
8. export class BookComponent implements OnInit {
9.
10. constructor(private displayBooks: BooksdataService) { }
11. books=this.displayBooks.books;
86 | P a g e S . S r i d h a r M E S G
12.
13. ngOnInit(): void {
14. this.books;
15. }
16.}
21. Save the files and check the output in the browser.
87 | P a g e S . S r i d h a r M E S G
.
88 | P a g e S . S r i d h a r M E S G
10.b Course Name: Angular JS
Module Name: Route Guards
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
Create a component named LoginComponent and add the following code to
the login.component.html file:
1. <h3 style="position: relative; left: 60px">Login Form</h3>
2. <div *ngIf="invalidCredentialMsg" style="color: red">
3. {{ invalidCredentialMsg }}
4. </div>
5. <br />
6. <div style="position: relative; left: 20px">
7. <form [formGroup]="loginForm" (ngSubmit)="onFormSubmit()">
8. <p>User Name <input formControlName="username" /></p>
9. <p>
10. Password
11. <input
12. type="password"
13. formControlName="password"
14. style="position: relative; left: 10px"
15. />
16. </p>
17. <p><button type="submit">Submit</button></p>
18. </form>
19.</div>
20.
21.
3. Create user.ts file under login folder and add the following code to user.ts file:
1. export class User {
90 | P a g e S . S r i d h a r M E S G
2. constructor(public userId: number, public username: string, public
password: string) { }
3. }
4. Add the following code to the login.service.ts file inside login folder:
1. import { Injectable } from '@angular/core';
2. import { Observable, of } from 'rxjs';
3. import { map } from 'rxjs/operators';
4. import { User } from './user';
5. const USERS = [
6. new User(1, 'user1', 'user1'),
7. new User(2, 'user2', 'user2')
8. ];
9. const usersObservable = of(USERS);
10.@Injectable({
11. providedIn: 'root'
12.})
13.export class LoginService {
14. private isloggedIn = false;
15. getAllUsers(): Observable<User[]> {
16. return usersObservable;
17. }
18. isUserAuthenticated(username: string, password: string):
Observable<boolean> {
19. return this.getAllUsers().pipe(
20. map(users => {
21. const Authenticateduser = users.find(user => (user.username ===
username) && (user.password === password));
22. if (Authenticateduser) {
23. this.isloggedIn = true;
24. } else {
25. this.isloggedIn = false;
26. }
27. return this.isloggedIn;
28. })
91 | P a g e S . S r i d h a r M E S G
29. );
30. }
31. isUserLoggedIn(): boolean {
32. return this.isloggedIn;
33. }
34.}
5. Create another service class called login-guard.service inside login folder and
add the following code:
1. import { inject} from '@angular/core';
2. import { Router } from '@angular/router';
3. import { LoginService } from './login.service';
4.
5. export const authGuard=()=>{
6. const loginService=inject(LoginService)
7. const router=inject(Router)
8.
9. if (loginService.isUserLoggedIn()) {
10. return true;
11. }
12. router.navigate(['/login']);
13. return false;
14.}
94 | P a g e S . S r i d h a r M E S G
10.c Course Name: Angular JS
Module Name: Asynchronous Routing
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
2. Write the code given below in the book-routing.module.ts file inside book
folder.
1. import { authGuard } from './../login/login-guard.service';
2. import { NgModule } from '@angular/core';
3. import { RouterModule, Routes } from '@angular/router';
4. import { BookComponent } from './book.component';
5. const bookRoutes: Routes = [
6. {
7. path: '',
8. component: BookComponent,
9. canActivate: [authGuard]
10. }
11.];
12.@NgModule({
13. imports: [RouterModule.forChild(bookRoutes)],
14. exports: [RouterModule]
15.})
16.export class BookRoutingModule { }
3. Create the book.module.ts file inside book folder and add the following
code
1. import { NgModule } from '@angular/core';
2. import { CommonModule } from '@angular/common';
3. import { BookComponent } from './book.component';
4. import { BookRoutingModule } from './book-routing.module';
5. @NgModule({
95 | P a g e S . S r i d h a r M E S G
6. imports: [CommonModule, BookRoutingModule],
7. declarations: [BookComponent]
8. })
9. export class BookModule { }
96 | P a g e S . S r i d h a r M E S G
5. Add the following code to the app.module.ts file
1. import { NgModule } from '@angular/core';
2. import { BrowserModule } from '@angular/platform-browser';
3. import { HttpClientModule } from '@angular/common/http';
4. import { FormsModule, ReactiveFormsModule } from '@angular/forms';
5. import { AppComponent } from './app.component';
6. import { BookComponent } from './book/book.component';
7. import { DashboardComponent } from './dashboard/dashboard.component';
8. import { BookDetailComponent } from './book-detail/book-
detail.component';
9. import { AppRoutingModule } from './app-routing.module';
10.import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
11.import { LoginComponent } from './login/login.component';
12.@NgModule({
13. imports: [BrowserModule, HttpClientModule,
ReactiveFormsModule,FormsModule, AppRoutingModule],
14. declarations: [AppComponent, LoginComponent, DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
15. providers: [],
16. bootstrap: [AppComponent]
17.})
18.export class AppModule { }
97 | P a g e S . S r i d h a r M E S G
Save the files and check the output in the browser.
98 | P a g e S . S r i d h a r M E S G
10.d Course Name: Angular JS
Module Name: Nested Routes Implement Child Routes to a submodule.
101 | P a g e S . S r i d h a r M E S G
8. Write the below code in book.component.ts:
1. import { Component, OnInit } from '@angular/core';
2. import { Router } from '@angular/router';
3. import { Book } from './book';
4. import { BookService } from './book.service';
5. @Component({
6. selector: 'app-book',
7. templateUrl: './book.component.html',
8. styleUrls: ['./book.component.css']
9. })
10.export class BookComponent implements OnInit {
11. books: Book[]=[];
12. errorMessage!: string;
13. constructor(private bookService: BookService, private router: Router) { }
14. getBooks() {
15. this.bookService.getBooks().subscribe({
16. next: books => {console.log(books);this.books = books},
17. error:error => this.errorMessage = <any>error
18. })
19. }
20. gotoDetail(book: Book): void {
21. this.router.navigate(['/books/detail/', book.id]);
22. }
23. ngOnInit(): void {
24. this.getBooks();
25. }
26.}
104 | P a g e S . S r i d h a r M E S G
105 | P a g e S . S r i d h a r M E S G
11.a Course Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Introduction to the CRUD Operations
Write MongoDB queries to perform CRUD operations on document
using insert(), find(), update(), remove()
CRUD Operations (Create, Read, Update, and Delete) are the basic set of
operations that allow users to interact with the MongoDB server.
As we know, to use MongoDB we need to interact with the MongoDB server
to perform certain operations like entering new data into the application,
updating data into the application, deleting data from the
106 | P a g e S . S r i d h a r M E S G
Method Description
db.createCollection() It is used to create an empty collection.
Create Operations Example
Let’s look at some examples of the Create operation from CRUD in
MongoDB.
107 | P a g e S . S r i d h a r M E S G
db.users.insertOne({
name: "Angela",
age: 27,
});
Output:
{
"acknowledged": true,
"insertedId" : ObjectId("64255335abfa5ebad9b5e2f7")
}
2. insertMany()
This method is used to insert multiple documents into a collection at once. It
takes an array of documents as its argument and returns a result object that
contains information about the insertion.
Syntax:
db.collectionName.insertMany();
Example:
db.users.insertMany([
{
name: "Angela",
age: 27,
},
{
name: "Dwight",
age: 30,
},
{
name: "Jim",
age: 29,
}
]);
Output:
{
"acknowledged": true,
"insertedIds" : [
108 | P a g e S . S r i d h a r M E S G
ObjectId("6425546aabfa5ebad9b5e2f8"),
ObjectId("6425546aabfa5ebad9b5e2f9"),
ObjectId("6425546aabfa5ebad9b5e2fa")
]
}
Both the insertOne() and insertMany() methods return a result object that
contains information about the insertion operation. The result object includes
the number of documents inserted, the unique _id field value of each inserted
document, and any write errors that occurred during the operation.
Read Operations
In MongoDB, read operations are used to retrieve data from the database.
1. find()
The find() method is used to retrieve data from a collection. It returns a cursor
that can be iterated to access all the documents that match the specified query
criteria.
Syntax:
db.collectionName.find(query, projection)
Query - It specifies the selection criteria for the documents to be retrieved. It
is an object that contains one or more key-value pairs, where each key
represents a field in the document and the value represents the value to match
for that field.
Projection - It specifies which fields to include or exclude in the result set. It
is an object that contains one or more key-value pairs, where each key
represents a field in the document and the value represents whether to include
(1) or exclude (0) the field in the result set.
Note: Both query and projection are optional.
Example:
db.users.find()
Output:
{ "_id" : ObjectId("64255335abfa5ebad9b5e2f7"), "name" : "Angela", "age"
: 27 }
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f8"), "name" : "Angela", "age"
: 27 }
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f9"), "name" : "Dwight", "age"
: 30 }
109 | P a g e S . S r i d h a r M E S G
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2fa"), "name" : "Jim", "age" : 29
}
The above example will retrieve all documents from the collection without
applying any filters or projecting any specific fields.
Example:
db.users.find({ age: { $gt: 29 } }, { name: 1, age: 1 })
Output:
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f9"), "name" : "Dwight", "age"
: 30 }
This command will return all the documents in the "users" collection where
the age is greater than 29, and only return the "name" and "age" fields.
2. findOne()
The findOne() method returns a single document object, or null if no
document is found. You can pass a query object to this method to filter the
results.
Syntax:
db.collectionName.findOne()
Example:
db.users.findOne({ name: "Jim" })
Output:
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2fa"), "name" : "Jim", "age" : 29
}
This returns the first document in the user's collection where the name field is
"Jim".
Update Operations
In MongoDB, the "update" operation is used to modify existing documents in
a collection.
Methods:
There are several ways to perform an update operation, including the
following:
1. updateOne()
The updateOne() method is used to update a single document that matches a
specified filter.
Syntax:
db.collectionName.updateOne(filter, update, options)
110 | P a g e S . S r i d h a r M E S G
Options include the following parameters:
• Upsert is an optional boolean that specifies whether to insert a new document
if no document matches the filter. If upsert is set to true and no document
matches the filter, a new document will be inserted. The default value of upsert
is false.
• WriteConcern is an optional document that specifies the level of
acknowledgement requested from MongoDB for write operations. If not
specified, the default write concern will be used.
Example:
db.users.updateOne({ name: "Angela" }, { $set: { email:
"[email protected]" } })
Output
{ "_id" : ObjectId("64255335abfa5ebad9b5e2f7"), "name" : "Angela", "age"
: 27, "email" : "[email protected]" }
In the example, we have used the $set operation.
Following are a few of the many available operations:
• $set: Sets the value of a field in a document. If the field does not exist, the set
will create it.
• $unset: Removes a field from a document.
• $inc: Increments the value of a field in a document by a specified amount.
• $push: Adds an element to the end of an array field in a document. If the field
does not exist, push will create it as an array with the specified element.
• $pull: Removes all occurrences of a specified value from an array field in a
document.
This command will update the email of the document in the "users" collection
where the name is "Angela" to [email protected].
2. updateMany
The updateMany() method is used to update multiple documents that match a
specified filter.
Syntax:
db.collectionName.updateMany(filter, update, options)
Example:
db.users.updateMany({ age: { $lt: 30 } }, { $set: { status: "active" } })
Output:
111 | P a g e S . S r i d h a r M E S G
{ "_id" : ObjectId("64255335abfa5ebad9b5e2f7"), "name" : "Angela", "age"
: 27, "email" : "[email protected]", "status" : "active" }
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f8"), "name" : "Angela", "age"
: 27, "status" : "active" }
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f9"), "name" : "Dwight", "age"
: 30 }
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2fa"), "name" : "Jim", "age" : 29,
"status" : "active" }
This command will update the status of all documents in the "users" collection
where the age is less than 30 to "active".
Delete Operations
In MongoDB, the "delete" operation is used to remove documents from a
collection.
There are several ways to perform a delete operation, including the
following:
1. deleteOne()
The deleteOne() method is used to remove a single document that matches a
specified filter.
Syntax:
db.collectionName.deleteOne(filter, options)
filter: Specifies deletion criteria using query operators. Specify an empty
document { } to delete the first document returned in the collection.
Options:
• WriteConcern (Optional): A document expressing the write concern. Omit
to use the default write concern.
• Collation (Optional): Specifies the collation to use for the operation.
Collation allows users to specify language-specific rules for string
comparison, such as rules for letter case and accent marks.
• Hint (Optional): A document or string that specifies the index to use to
support the query predicate.
Example:
db.users.deleteOne({ name: "Angela" })
Output:
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f8"), "name" : "Angela", "age"
: 27, "status" : "active" }
112 | P a g e S . S r i d h a r M E S G
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f9"), "name" : "Dwight", "age"
: 30 }
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2fa"), "name" : "Jim", "age" : 29,
"status" : "active" }
This command will remove the first document in the "users" collection where
the name is "Angela".
2. deleteMany()
The deleteMany() method is used to remove multiple documents that match a
specified filter.
Syntax:
db.collectionName.deleteMany(filter, options)
Example:
db.users.deleteMany({ age: { $lt: 30 } })
Output:
{ "_id" : ObjectId("6425546aabfa5ebad9b5e2f9"), "name" : "Dwight", "age"
: 30 }
This command will remove all documents in the "users" collection where the
age is less than 30.
3. drop()
The drop() method is used to remove an entire collection.
Syntax:
db.collectionName.drop()
Example:
db.users.drop()
Output:
true
This command will remove the users collection.
Note: This operation is irreversible, and all data in the collection will be
permanently deleted.
>use students
113 | P a g e S . S r i d h a r M E S G
>db.createCollection("studentgrades")>
>db.studentgrades.insertMany(
[
{name: "Barry", subject: "Maths", score: 92},
{name: "Kent", subject: "Physics", score: 87},
{name: "Harry", subject: "Maths", score: 99, notes: "Exceptional
Performance"},
{name: "Alex", subject: "Literature", score: 78},
{name: "Tom", subject: "History", score: 65, notes: "Adequate"}
]
)
db.studentgrades.find({},{_id:0})
Result
Creating indexes
When creating documents in a collection, MongoDB creates a unique index
using the _id field. MongoDB refers to this as the Default _id Index. This
default index cannot be dropped from the collection.
When querying the test data set, you can see the _id field which will be utilized
as the default index:
db.studentgrades.find().pretty()
Result:
114 | P a g e S . S r i d h a r M E S G
Now let’s create an index. To do that, you can use the createIndex method
using the following syntax:
115 | P a g e S . S r i d h a r M E S G
The best option is to use the name option to define a custom index name when
creating an index. Indexes cannot be renamed after creation. (The only way to
rename an index is to first drop that index, which we show below, and recreate
it using the desired name.)
Let’s create an index using the name field in the studentgrades collection and
name it as student name index.
db.studentgrades.createIndex(
{name: 1},
{name: "student name index"}
)
Result:
Finding indexes
You can find all the available indexes in a MongoDB collection by using the
getIndexes method. This will return all the indexes in a specific collection.
db.<collection>.getIndexes()
Let’s view all the indexes in the studentgrades collection using the following
command:
db.studentgrades.getIndexes()
Result:
116 | P a g e S . S r i d h a r M E S G
The output contains the default _id index and the user-created index student
name index.
Dropping indexes
To delete an index from a collection, use the dropIndex method while
specifying the index name to be dropped.
You can also use the index field value for removing an index without a defined
name:
db.studentgrades.dropIndex({name:1})
117 | P a g e S . S r i d h a r M E S G
Result:
The dropIndexes command can also drop all the indexes excluding the default
_id index.
db.studentgrades.dropIndexes()
Result:
db.studentgrades.createIndex({name: 1})
Result:
118 | P a g e S . S r i d h a r M E S G
The above index will sort the data in ascending order using the name field.
You can use the sort() method to see how the data will be represented in the
index.
db.studentgrades.find({},{_id:0}).sort({name:1})
Result:
Compound index
You can use multiple fields in a MongoDB document to create a compound
index. This type of index will use the first field for the initial sort and then sort
by the preceding fields.
db.studentgrades.find({},{_id:0}).sort({subject:1, score:-1})
Result:
Multikey index
119 | P a g e S . S r i d h a r M E S G
MongoDB supports indexing array fields. When you create an index for a field
containing an array, MongoDB will create separate index entries for every
element in the array. These multikey indexes enable users to query documents
using the elements within the array.
MongoDB will automatically create a multikey index when encountered with
an array field without requiring the user to explicitly define the multikey type.
Let’s create a new data set containing an array field to demonstrate the
creation of a multikey index.
db.createCollection("studentperformance")
db.studentperformance.insertMany(
[
{name: "Barry", school: "ABC Academy", grades: [85, 75, 90, 99] },
{name: "Kent", school: "FX High School", grades: [74, 66, 45, 67]},
{name: "Alex", school: "XYZ High", grades: [80, 78, 71, 89]},
]
)
db.studentperformance.find({},{_id:0}).pretty()
Result:
120 | P a g e S . S r i d h a r M E S G
db.studentperformance.createIndex({grades:1})
Result:
db.studentgrades.createIndex({notes:1},{sparse: true})
Result:
In the previous studentgrades collection, if you create an index using the notes
field, it will index only two documents as the notes field is present only in two
documents.
122 | P a g e S . S r i d h a r M E S G
Partial index
The partial index functionality allows users to create indexes that match a
certain filter condition. Partial indexes use the partialFilterExpression option
to specify the filter condition.
db.studentgrades.createIndex(
{name:1},
{partialFilterExpression: {score: { $gte: 90}}}
)
Result:
The above code will create an index for the name field but will only include
documents in which the value of the score field is greater than or equal to 90.
Unique index
The unique property enables users to create a MongoDB index that only
includes unique values. This will:
• Reject any duplicate values in the indexed field
• Limit the index to documents containing unique values
db.studentgrades.createIndex({name:1},{unique: true})
Result:
123 | P a g e S . S r i d h a r M E S G
The above-created index
12.a Course Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Create and Delete Databases and Collections
Write MongoDB queries to Create and drop databases and collections.
Creating a MongoDB Database
How to view existing databases
Before we begin creating new databases, it's helpful to get familiar with some of the
methods that MongoDB provides for finding information about existing databases.
This can help you understand the current state of the system before you begin making
changes.
To display all of the databases on the system that you have access to, use the show
dbs method:
>show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
MongoDB will respond with the names of all of the accessible databases on the
system as well as a summary of their current storage space.
To see which database you are currently set to operate on, use the db.getName()
command or its shorthand alias, db:
db
test
You may find that you are currently using a database that wasn't listed by the show
dbs command. This is because in MongoDB, until you write the first document to
the database, the database is not actually created. So, in the example output above,
the shell is prepared to operate on a test database, but since it does not exist yet, it
will not be returned by the show dbs command.
124 | P a g e S . S r i d h a r M E S G
>db.stats()
{
"db" : "admin",
"collections" : 3,
"views" : 0,
"objects" : 4,
"avgObjSize" : 278.25,
"dataSize" : 1113,
"storageSize" : 86016,
"indexes" : 5,
"indexSize" : 147456,
"totalSize" : 233472,
"scaleFactor" : 1,
"fsUsedSize" : 2876923904,
"fsTotalSize" : 25832407040,
"ok" : 1
}
The output shows information about the number of collections within the database,
storage statistics, index information, and more.
How to create databases
MongoDB does not have an explicit command for creating a new database. Instead,
as mentioned earlier, you have to instead indicate to MongoDB that you want to
write new documents to a new database. When those documents are created, they
will implicitly create the database.
To prepare MongoDB to write to a new database, issue the use command to switch
to a non-existent database.
Here, we will set up MongoDB to create a new database called playground:
>use playground
switched to db playground
If you check your current database, it will confirm that the playground database is
currently the target of database-related commands:
db
playground
125 | P a g e S . S r i d h a r M E S G
However, as mentioned before, since we have not yet created any documents, the
database itself has not been created yet:
>show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
To actually create the new database, we will need to create something first.
How to view the collections in a database
In MongoDB, collections are structures used to group documents together using
whatever system of categorization you want to implement. They live inside
databases and store documents.
You can see the available collections in the database you're currently using by using
the show collections method.
Here, we'll switch to the admin database that has some collections available to
demonstrate:
>use admin
>show collections
system.roles
system.users
system.version
Alternatively, you can retrieve the same collection names in an array using the
db.getCollectionNames() method:
db.getCollectionNames()
[ "system.roles", "system.users", "system.version" ]
To show additional information about the collections in the current database, use the
db.getCollectionInfos() method:
db.getCollectionInfos()
[
{
"name" : "system.roles",
"type" : "collection",
"options" : {
},
"info" : {
126 | P a g e S . S r i d h a r M E S G
"readOnly" : false,
"uuid" : UUID("776b1fd7-6014-4191-b33c-21350b590627")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
},
{
"name" : "system.users",
"type" : "collection",
"options" : {
},
"info" : {
"readOnly" : false,
"uuid" : UUID("8c824fd1-2150-4413-8fac-0b77d16505e5")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
},
{
"name" : "system.version",
"type" : "collection",
"options" : {
},
127 | P a g e S . S r i d h a r M E S G
"info" : {
"readOnly" : false,
"uuid" : UUID("7501483a-45cc-492e-a1fd-ccb4349650cb")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
}
]
You can also optionally pass in a document to the command to filter the results. For
example, if you are only interested in seeing the information about the
system.version collection, you could type:
db.getCollectionInfos(
{
name: "system.version"
}
)
[
{
"name" : "system.version",
"type" : "collection",
"options" : {
},
"info" : {
"readOnly" : false,
"uuid" : UUID("7501483a-45cc-492e-a1fd-ccb4349650cb")
},
"idIndex" : {
"v" : 2,
"key" : {
128 | P a g e S . S r i d h a r M E S G
"_id" : 1
},
"name" : "_id_"
}
}
]
To check how many documents a collection contains, use the
db.<collection>.count() method. For instance, the following command checks how
many documents are in the system.users collection:
db.system.users.count()
2
To view basic statistics about the collections in the current database, use the
db.printCollectionStats() method:
db.printCollectionStats()
The command may output more information than you can easily consume, but
contains, but is helpful in some scenarios where you need to take a deep look at the
characteristics of a collection.
How to create collections
To create a new collection, there are two options: you can create collections either
implicitly or explicitly.
As with databases, MongoDB can automatically create collections the first time a
document is written to them. This method tells MongoDB to create a new collection
by inserting a document into a collection that does not exist yet.
For instance, we can change back to the playground database that we were interested
in earlier. Once we are in that namespace, we can insert a new document into a
collection by calling the insert.() command on the name we'd like to use for the new
collection. Here, we can create a document about a slide in a new collection called
equipment:
use playground
>db.equipment.insert({name: "slide"})
switched to db playground
>WriteResult({ "nInserted" : 1 })
The output indicates that one document was written. The above command performed
three separate actions. First, MongoDB created the playground database that we'd
129 | P a g e S . S r i d h a r M E S G
referenced in our use command. It also created the equipment collection within the
database since we call the insert() command on that collection name. Finally, it
creates the actual document within the equipment collection using the input we
provided to the insert() command.
You can verify that all of these actions have been performed with the following
commands:
>show dbs
>show collections
>db.equipment.count()
>db.equipment.find()
The output should show that the playground database is now among the listed
databases, that the equipment collection is listed, that there is one document within
the equipement collection, and that the document is the {name: "slide"} document
we inserted in the command.
The other option to use to create collections is to explicitly use the
db.createCollection() method. This allows you to create collections without adding
any documents to them.
For example, you can create a new collection in the playground database called
maintenance.requests by typing:
>db.createCollection("maintenance.requests")
{ "ok" : 1 }
We can verify that the new collection shows up when we query for it, but that it has
no documents:
>show collections
db.maintenance.requests.count()
equipment
maintenance.requests
0
The db.createCollection() method is primarily useful because it allows you to specify
various options upon creation. For example, we may want to create a create a capped
collection, which is a collection that maintains an upper limit on its allocated size it
stores by deleting its oldest document when full.
To create a capped collection called notifications that can store, at most, 10240 bytes
of information, you could call:
130 | P a g e S . S r i d h a r M E S G
db.createCollection(
"notifications",
{
capped: true,
size: 10240
}
)
{ "ok" : 1}
This will create a capped notification collection, which we can verify by typing:
db.getCollecitonInfos({"options.capped": true})
[
{
"name" : "notifications",
"type" : "collection",
"options" : {
"capped" : true,
"size" : 10240
},
"info" : {
"readOnly" : false,
"uuid" : UUID("dff7bfb0-1cfc-4170-ba60-fbb834ac6925")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
}
}
]
How to delete collections
To delete a collection, you can use the drop() method on the collection itself.
For example, to drop the capped notifications collection we created, you can type:
131 | P a g e S . S r i d h a r M E S G
db.notifications.drop()
true
You can verify that the operation was successful by listing the collections in the
current database again:
>show collections
equipment
maintenance.requests
How to delete databases
To delete a whole database, call the db.dropDatabase() command. This will delete
the current database, so be sure you are on the correct database before executing:
use playground
>db.dropDatabase()
switched to db playground
{ "dropped" : "playground", "ok" : 1 }
If you check the list of available databases, playground is no longer displayed:
>show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
Since we haven't switched to a new database yet, MongoDB is still set up to create
a playground database should we choose to add a new collection or document. You
can verify this with the db command:
db
playground
132 | P a g e S . S r i d h a r M E S G
12.bCourse Name: MongoDB Essentials - A Complete MongoDB Guide
Module Name: Introduction to MongoDB Queries
Write MongoDB queries to work with records using find(), limit(), sort(),
createIndex(), aggregate().
Limit:
by using the Limit modifier, we can limit the number of documents that can be
returned in a query.
Example:
First check the data inside the collection “student”
db.students.find()
testset:PRIMARY>db.students.find()
{ "_id" : ObjectId("59245acd5273c93ad95b109b"), "firstname" : "Maria", "city" :
"Banglore", "age" : 21 }
{ "_id" : ObjectId("59246d4b5273c93ad95b109c"), "firstname" : "sneha", "city" :
"Delhi", "age" : 21 }
{ "_id" : ObjectId("59246d7b5273c93ad95b109d"), "firstname" : "jay", "city" :
"toronto", "age" : 21 }
{ "_id" : ObjectId("59254ec6c2c4480ef9a1e5bb"), "firstname" : "harry", "city" :
"texas", "age" : 24 }
{ "_id" : ObjectId("59254f0cc2c4480ef9a1e5bc"), "firstname" : "rita", "city" :
"california", "age" : 22 }
133 | P a g e S . S r i d h a r M E S G
{ "_id" : ObjectId("59254f2dc2c4480ef9a1e5bd"), "firstname" : "prasad", "city" :
"newyork", "age" : 26 }
{ "_id" : ObjectId("59254f47c2c4480ef9a1e5be"), "firstname" : "devi", "city" :
"ohio", "age" : 26 }
Limit the data you want as result
db.students.find().limit(5).pretty();
testset:PRIMARY>db.students.find().limit(5).pretty();
{
"_id" : ObjectId("59245acd5273c93ad95b109b"),
"firstname" : "Maria",
"city" : "Banglore",
"age" : 21
}
{
"_id" : ObjectId("59246d4b5273c93ad95b109c"),
"firstname" : "sneha",
"city" : "Delhi",
"age" : 21
}
{
"_id" : ObjectId("59246d7b5273c93ad95b109d"),
"firstname" : "jay",
"city" : "toronto",
"age" : 21
}
{
"_id" : ObjectId("59254ec6c2c4480ef9a1e5bb"),
"firstname" : "harry",
"city" : "texas",
"age" : 24
}
{
"_id" : ObjectId("59254f0cc2c4480ef9a1e5bc"),
"firstname" : "rita",
"city" : "california",
134 | P a g e S . S r i d h a r M E S G
"age" : 22
}
Sort Order:
By using the sort modifier, we can sort the result in a ascending order or descending
order.
Example:
Sort the data in ascending order as result
db.students.find().sort({“firstname”:1});
testset:PRIMARY>db.students.find().sort({"firstname":1});
{ "_id" : ObjectId("59245acd5273c93ad95b109b"), "firstname" : "Maria", "city" :
"Banglore", "age" : 21 }
{ "_id" : ObjectId("59254f47c2c4480ef9a1e5be"), "firstname" : "devi", "city" :
"ohio", "age" : 26 }
{ "_id" : ObjectId("59254ec6c2c4480ef9a1e5bb"), "firstname" : "harry", "city" :
"texas", "age" : 24 }
{ "_id" : ObjectId("59246d7b5273c93ad95b109d"), "firstname" : "jay", "city" :
"toronto", "age" : 21 }
{ "_id" : ObjectId("59254f2dc2c4480ef9a1e5bd"), "firstname" : "prasad", "city" :
"newyork", "age" : 26 }
{ "_id" : ObjectId("59254f0cc2c4480ef9a1e5bc"), "firstname" : "rita", "city" :
"california", "age" : 22 }
{ "_id" : ObjectId("59246d4b5273c93ad95b109c"), "firstname" : "sneha", "city" :
"Delhi", "age" : 21 }
Sort the data in descending order as result
db.students.find().sort({“firstname”:-1});
testset:PRIMARY>db.students.find().sort({"firstname":-1});
{ "_id" : ObjectId("59246d4b5273c93ad95b109c"), "firstname" : "sneha", "city" :
"Delhi", "age" : 21 }
{ "_id" : ObjectId("59254f0cc2c4480ef9a1e5bc"), "firstname" : "rita", "city" :
"california", "age" : 22 }
{ "_id" : ObjectId("59254f2dc2c4480ef9a1e5bd"), "firstname" : "prasad", "city" :
"newyork", "age" : 26 }
{ "_id" : ObjectId("59246d7b5273c93ad95b109d"), "firstname" : "jay", "city" :
"toronto", "age" : 21 }
135 | P a g e S . S r i d h a r M E S G
{ "_id" : ObjectId("59254ec6c2c4480ef9a1e5bb"), "firstname" : "harry", "city" :
"texas", "age" : 24 }
{ "_id" : ObjectId("59254f47c2c4480ef9a1e5be"), "firstname" : "devi", "city" :
"ohio", "age" : 26 }
{ "_id" : ObjectId("59245acd5273c93ad95b109b"), "firstname" : "Maria", "city" :
"Banglore", "age" : 21 }
Creating indexes
When creating documents in a collection, MongoDB creates a unique index using
the _id field. MongoDB refers to this as the Default _id Index. This default index
cannot be dropped from the collection.
When querying the test data set, you can see the _id field which will be utilized as
the default index:
db.studentgrades.find().pretty()
Result:
136 | P a g e S . S r i d h a r M E S G
db.studentgrades.createIndex(
{name: 1},
{name: "student name index"}
)
Result:
137 | P a g e S . S r i d h a r M E S G
The aggregate() Method
For the aggregation in MongoDB, you should use aggregate() method.
Syntax
Basic syntax of aggregate() method is as follows −
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Example
In the collection you have the following data −
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'Sridhar',
url: 'http://www.sridhar.com’,
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'Sridhar',
url: 'http://www.Sridhar.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 10
},
138 | P a g e S . S r i d h a r M E S G
{
_id: ObjectId(7df78ad8902e)
title: 'Neo4j Overview',
description: 'Neo4j is no sql database',
by_user: 'Neo4j',
url: 'http://www.neo4j.com',
tags: ['neo4j', 'database', 'NoSQL'],
likes: 750
},
Now from the above collection, if you want to display a list stating how many
tutorials are written by each user, then you will use the following aggregate()
method −
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "tutorials point", "num_tutorial" : 2 }
{ "_id" : "Neo4j", "num_tutorial" : 1 }
139 | P a g e S . S r i d h a r M E S G