0% found this document useful (0 votes)
28 views

Angular - 2 Lab Manual

Angular 2 lab manual

Uploaded by

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

Angular - 2 Lab Manual

Angular 2 lab manual

Uploaded by

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

MEAN STACK TECHNOLOGIES-MODULE II- ANGULAR JS,

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

3. Open hello.component.ts file and create a property called courseName of type


string and initialize it to "Angular" as shown below in Line number 9
1. import { Component, OnInit } from '@angular/core';
2.
3. @Component({
4. selector: 'app-hello',
5. templateUrl: './hello.component.html',
6. styleUrls: ['./hello.component.css']
7. })
8. export class HelloComponent implements OnInit {
9. courseName: string = "Angular";
10.
11. constructor() { }
12.
13. ngOnInit() {
14. }

1|Page S.Sridhar MESG


15.
16.}

4. Open hello.component.html and display the courseName as shown below in Line


2
1. <p>
2. Hello {{ courseName }}
3. </p>
5. Open hello.component.css and add the following styles for the paragraph element
1. p {
2. color:blue;
3. font-size:20px;
4. }

6. Open app.module.ts file and add HelloComponent to bootstrap property as shown


below in Line 11 to load it for execution
1. import { NgModule } from '@angular/core';
2. import { BrowserModule } from '@angular/platform-browser';
3.
4. import { AppRoutingModule } from './app-routing.module';
5. import { AppComponent } from './app.component';
6. import { HelloComponent } from './hello/hello.component';
7.
8. @NgModule({
9. imports: [BrowserModule,AppRoutingModule],
10. declarations: [AppComponent, HelloComponent],
11. providers: [],
12. bootstrap: [HelloComponent]
13.})
14.export class AppModule { }

2|Page S.Sridhar MESG


7. Open index.html and load the hello component by using its selector name i.e.,
app-hello as shown below in Line 11
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-hello></app-hello>
12.</body>
13.</html>

8. Now run the application by giving the following command


1. D:\MyApp>ng serve –open

Output:

3|Page S.Sridhar MESG


1.b Course Name: Angular JS
Module Name: Components and Modules
Create a new component called hello and render Hello Angular on the page

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.

Type the following command to run the application

D:\MyApp>ng serve --open

ng serve will build and run the application

4|Page S.Sridhar MESG


--open option will show the output by opening a browser automatically with the
default port.

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)

D:\MyApp>ng serve --open --port 3000


Following is the output of the MyApp Application
A screenshot of myApp Angular demo application running on browser with port
number 4200.

Creating a component using Angular CLI


Exploring the files created
Problem Statement: Creating a new component called hello and rendering Hello
Angular on the page as shown below

5|Page S.Sridhar MESG


1. In 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

3. Open hello.component.ts file and create a property called courseName of type


string and initialize it to "Angular" as shown below in Line number 9
1. import { Component, OnInit } from '@angular/core';
2. @Component({
3. selector: 'app-hello',
4. templateUrl: './hello.component.html',
5. styleUrls: ['./hello.component.css']
6. })
7. export class HelloComponent implements OnInit {
8. courseName: string = "Angular";
9. constructor() { }
10. ngOnInit() {
11. }
12.}
4. Open hello.component.html and display the courseName as shown below in Line
2

5. Open hello.component.css and add the following styles for the paragraph element
1. p {
2. color:blue;
3. font-size:20px;
4. }

6. Open app.module.ts file and add HelloComponent to bootstrap property as shown


below in Line 11 to load it for execution
1. import { NgModule } from '@angular/core';
2. import { BrowserModule } from '@angular/platform-browser';

6|Page S.Sridhar MESG


3. import { AppRoutingModule } from './app-routing.module';
4. import { AppComponent } from './app.component';
5. import { HelloComponent } from './hello/hello.component';
6. @NgModule({
7. imports: [BrowserModule,AppRoutingModule],
8. declarations: [AppComponent, HelloComponent],
9. providers: [],
10. bootstrap: [HelloComponent]
11.})
12.export class AppModule { }
7. Open index.html and load the hello component by using its selector name i.e.,
app-hello as shown below in Line 11
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-hello></app-hello>
12.</body>
13.</html>
8. Now run the application by giving the following command
1. D:\MyApp>ng serve --open

7|Page S.Sridhar MESG


1.c Course Name: Angular JS
Module Name: Elements of Template
Add an event to the hello component template and when it is clicked, it should
change the courseName.

Templates Basics

By default, Angular CLI uses the external template.

It binds the external template with a component using templateUrl option.

Example

app.component.html

1. <h1> Welcome </h1>


2. <h2> Course Name: {{ courseName }}</h2>

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. courseName = "Angular";
9. }

Line 5: templateUrl property is used to bind an external template file with the
component.

Output:

8|Page S.Sridhar MESG


9|Page S.Sridhar MESG
1.d Course Name: Angular JS Module Name: Change Detection progressively
building the PoolCarz application

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.

In the mCart application, there is a welcome screen displayed on application launch,


as shown here.

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

1. Code for the LoginComponent template is present in


the login.component.html file.
1. <!-- Login form-->
2. <div class="container container-styles">
3. <div class="col-xs-7 col-xs-offset-3">
4. <div class="panel panel-primary">
5. <div class="panel-heading">Login</div>
6. <div class="panel-body padding">
7. <form class="form-horizontal"
[formGroup]="loginForm">
8. <div class="form-group" >
9. <label for="name" class="col-xs-4 control-label" style="text-align:left">User
Name</label>
10.<div class="col-xs-8">
11.<input type="text" class="form-control"
[ngClass]="{'valid':loginForm.controls['userName'].valid,

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 { }

4. Ensure the index.html displays app-root.


1. <!doctype html>

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.

ngFor directive is used to iterate over-collection of data i.e., arrays


Syntax:
1. *ngFor = "expression"
Example:
app.component.ts
1. ...
2. export class AppComponent {
3. courses: any[] = [
4. { id: 1, name: "TypeScript" },
5. { id: 2, name: "Angular" },
6. { id: 3, name: "Node JS" },
7. { id: 1, name: "TypeScript" }
8. ];
9. }
Line 3-8: Creating an array of objects

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

1. 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. courses: any[] = [
10. { id: 1, name: 'TypeScript' },
11. { id: 2, name: 'Angular' },
12. { id: 3, name: 'Node JS' },
13. { id: 1, name: 'TypeScript' }
14. ];
15.}
2. Write the below-given code in app.component.html
1. <ul>
2. <li *ngFor="let course of courses; let i = index">
3. {{ i }} - {{ course.name }}
4. </li>
5. </ul>
3. Save the files and check the output in the browser

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:

1. 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. choice = 0;
10.
11. nextChoice() {
12. this.choice++;
13. }
14.}
2. Write the below-given code in app.component.html
1. <h4>
2. Current choice is {{ choice }}
3. </h4>
4.
5. <div [ngSwitch]="choice">
6. <p *ngSwitchCase="1">First Choice</p>
7. <p *ngSwitchCase="2">Second Choice</p>
8. <p *ngSwitchCase="3">Third Choice</p>
9. <p *ngSwitchCase="2">Second Choice Again</p>
10. <p *ngSwitchDefault>Default Choice</p>
11.</div>

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

2. Above command will add MessageDirective class to the declarations property


in the app.module.ts file
1. import { BrowserModule } from '@angular/platform-browser';
2. import { NgModule } from '@angular/core';
3. import { AppComponent } from './app.component';
4. import { MessageDirective } from './message.directive';
5. @NgModule({
6. declarations: [
7. AppComponent,
8. MessageDirective
9. ],
10. imports: [
11. BrowserModule
12. ],
13. providers: [],
14. bootstrap: [AppComponent]
15. })
16. export class AppModule { }
17.
3. Open the message.directive.ts file and add the following code
1. import { Directive, ElementRef, Renderer2, HostListener, Input } from
'@angular/core';
2. @Directive({

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

1. 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. isBordered = true;
10.}
2. Write the below-given code in app.component.html
1. <div [ngClass]="{bordered: isBordered}">
2. Border {{ isBordered ? "ON" : "OFF" }}
3. </div>
3. In app.component.css, add the following CSS class
1. .bordered {
2. border: 1px dashed black;
3. background-color: #eee;
4. }
Output:

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

2. Above command will add MessageDirective class to the declarations property


in the app.module.ts file
1. import { BrowserModule } from '@angular/platform-browser';
2. import { NgModule } from '@angular/core';
3. import { AppComponent } from './app.component';
4. import { MessageDirective } from './message.directive';
5. @NgModule({
6. declarations: [
7. AppComponent,
8. MessageDirective
9. ],
10. imports: [
11. BrowserModule
12. ],
13. providers: [],
14. bootstrap: [AppComponent]
15. })
16. export class AppModule { }
17.

3. Open the message.directive.ts file and add the following code


1. import { Directive, ElementRef, Renderer2, HostListener, Input } from
'@angular/core';
2. @Directive({
3. selector: '[appMessage]',
4. })

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.

4.b Course Name: Angular JS


Module Name: Attribute Binding
Binding colspan attribute of a table element to the class property.
Problem Statement: Binding colspan attribute of a table element to the class
property to display the following output.

Write the below-given code in app.component.ts

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.

Some style bindings will have a unit extension.

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.

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 {

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>

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 { FormsModule } from '@angular/forms';
4. import { AppComponent } from './app.component';
5. @NgModule({
6. declarations: [
7. AppComponent
8. ],
9. imports: [
10. BrowserModule,
11. FormsModule
12. ],
13. providers: [],
14. bootstrap: [AppComponent]
15.})
16.export class AppModule { }
4. Save the files and check the output in the browser

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.

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. title = 'product details';
10. productCode = 'PROD_P001';
11. productName = 'Laptop';
12.}
2. Write the below-given code in app.component.html
1. <h3> {{ title | titlecase}} </h3>
2. <table style="text-align:left">
3. <tr>
4. <th> Product Code </th>
5. <td> {{ productCode | lowercase }} </td>
6. </tr>
7. <tr>
8. <th> Product Name </th>
9. <td> {{ productName | uppercase }} </td>
10. </tr>
11.</table>
3. Save the files and check the output in the browser.

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.

1. 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. title = 'product details';
10. productCode = 'PROD_P001';
11. productName = 'Apple MPTT2 MacBook Pro';
12. productPrice = 217021;
13. purchaseDate = '1/17/2018';
14. productTax = '0.1';
15. productRating = 4.92;
16.}

2. Write the below-given code in app.component.html


1. <h3> {{ title | titlecase}} </h3>
2. <table style="text-align:left">
3. <tr>
4. <th> Product Code </th>
5. <td> {{ productCode | slice:5:9 }} </td>
6. </tr>

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 { }

4. Save the files and check the output in the browser

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

2. CoursesListComponent class will be added in the app.module.ts file


1. import { BrowserModule } from '@angular/platform-browser';
2. import { NgModule } from '@angular/core';
3. import { AppComponent } from './app.component';
4. import { CoursesListComponent } from './courses-list/courses-
list.component';
5.
6. @NgModule({
7. declarations: [
8. AppComponent,
9. CoursesListComponent
10. ],
11. imports: [
12. BrowserModule
13. ],
14. providers: [],
15. bootstrap: [AppComponent]
16.})
17.export class AppModule { }

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

6.a Course Name: Angular JS


Module Name: Passing data from Container Component to Child Component
Create an AppComponent that displays a dropdown with a list of courses as
values in it. Create another component called the CoursesList component and

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.}

2. Open courses-list.component.html and add the following code


1. <table border="1" *ngIf="course.length > 0">
2. <thead>
3. <tr>
4. <th>Course ID</th>
5. <th>Course Name</th>

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>

3. Add the following in app.component.html


1. <h2>Course Details</h2>
2.
3. Select a course to view
4. <select #course (change)="name = course.value">
5. <option value="Node JS">Node JS</option>
6. <option value="Typescript">Typescript</option>
7. <option value="Angular">Angular</option>
8. <option value="React JS">React JS</option></select><br /><br />
9.
10.<app-courses-list [cName]="name"></app-courses-list>
4. Add the following in app.component.ts
1. import { Component } from '@angular/core';
2.
3. @Component({
4. selector: 'app-root',
5. styleUrls: ['./app.component.css'],
6. templateUrl: './app.component.html'
7. })
8. export class AppComponent {
9. name!: string;
10.}

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>

4. 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. message!: string;
9. courseReg(courseName: string) {
10. this.message = `Your registration for ${courseName} is successful`;
11. }
12.}

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:

6.d Course Name: Angular JS


Module Name: Component Life Cycle
Override component life-cycle hooks and logging the corresponding messages to
understand the flow.

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.

Write the below-given code in app.component.ts


1. import {
2. Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked,
3. AfterViewInit, AfterViewChecked,
4. OnDestroy
5. } from '@angular/core';
6. @Component({
7. selector: 'app-root',
8. styleUrls: ['./app.component.css'],
9. templateUrl: './app.component.html'
10.})
11.export class AppComponent implements OnInit, DoCheck,
12. AfterContentInit, AfterContentChecked,
13. AfterViewInit, AfterViewChecked,
14. OnDestroy {
15. data = 'Angular';
16. ngOnInit() {
17. console.log('Init');
18. }
19. ngDoCheck(): void {
20. console.log('Change detected');
21. }
22. ngAfterContentInit(): void {
23. console.log('After content init');
24. }
25. ngAfterContentChecked(): void {
26. console.log('After content checked');
27. }
28. ngAfterViewInit(): void {
29. console.log('After view init');
30. }
31. ngAfterViewChecked(): void {
50 | P a g e S . S r i d h a r M E S G
32. console.log('After view checked');
33. }
34. ngOnDestroy(): void {
35. console.log('Destroy');
36. }
37.}
2. Write the below-given code in app.component.html
1. <div>
2. <h1>I'm a container component</h1>
3. <input type="text" [(ngModel)]="data" />
4. <app-child [title]="data"></app-child>
5. </div>

3. Write the below-given code in child.component.ts


1. import { Component, OnChanges, Input } from '@angular/core';
2. @Component({
3. selector: 'app-child',
4. templateUrl: './child.component.html',
5. styleUrls: ['./child.component.css']
6. })
7. export class ChildComponent implements OnChanges {
8. @Input() title!: string;
9. ngOnChanges(changes: any): void {
10. console.log('changes in child:' + JSON.stringify(changes));
11. }
12.}

4. Write the below-given code in child.component.html


1. <h2>Child Component</h2>
2. <h2>{{title}}</h2>
5. Ensure FormsModule is present in the imports section of the AppModule.
6. Save the files and check the output in the browser.

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

2. Create a component called RegistrationForm using the following CLI command


1. ng generate component RegistrationForm

3. Add the following code in the registration-form.component.ts file


1. import { Component, OnInit } from '@angular/core';
2. import { FormBuilder, 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. });
26. }
53 | P a g e S . S r i d h a r M E S G
27.
28.}

4. Write the below-given code in registration-form.component.html


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']">
20. This field is required!
21. </p>
22. </div>
23. </div>
24. <div class="form-group">
25. <fieldset formGroupName="address">
26. <legend>Address:</legend>

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. }

6. Write the below-given code in app.component.html


1. <app-registration-form></app-registration-form>
7. Save the files and check the output in the browser

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>

3. Save the files and check the output in the browser

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.}

6. Add the following code in the book.component.ts file


1. import { Component, OnInit } from '@angular/core';
2. import { Book } from './book';
3. import { BookService } from './book.service';
4.
5. @Component({
6. selector: 'app-book',
7. templateUrl: './book.component.html',
8. styleUrls: ['./book.component.css']
9. })
10.export class BookComponent implements OnInit {
11.
12. books!: Book[];
13.
14. constructor(private bookService: BookService) { }
15. getBooks() {
16. this.books = this.bookService.getBooks();
17. }
18. ngOnInit() {
19. this.getBooks();
20. }
21.}

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

Why RxJS Observables?


Angular team has recommended Observables for asynchronous calls because of the
following reasons:
1. Promises emit a single value whereas observables (streams) emit many values
2. Observables can be cancellable where Promises are not cancellable. If an
HTTP response is not required, observables allow us to cancel the subscription
whereas promises execute either success or failure callback even if the results
are not required.
3. Observables support functional operators such as map, filter, reduce, etc.,

Create and use an observable in Angular


Example:
app.component.ts
1. import { Component } from '@angular/core';
2. import { Observable } from 'rxjs';
3.
4. @Component({
5. selector: 'app-root',
6. styleUrls: ['./app.component.css'],
7. templateUrl: './app.component.html'
8. })
9. export class AppComponent {
10.
11. data!: Observable<number>;
12. myArray: number[] = [];
13. errors!: boolean;
65 | P a g e S . S r i d h a r M E S G
14. finished!: boolean;
15.
16. fetchData(): void {
17. this.data = new Observable(observer => {
18. setTimeout(() => { observer.next(11); }, 1000),
19. setTimeout(() => { observer.next(22); }, 2000),
20. setTimeout(() => { observer.complete(); }, 3000);
21. });
22. this.data.subscribe((value) => this.myArray.push(value),
23. error => this.errors = true,
24. () => this.finished = true);
25. }
26.}
Line 2: imports Observable class from rxjs module
Line 11: data is of type Observable which holds numeric values
Line 16: fetchData() is invoked on click of a button
Line 17: A new Observable is created and stored in the variable data
Line 18-20: next() method of Observable sends the given data through the stream.
With a delay of 1,2 and 3 seconds, a stream of numeric values will be sent.
Complete() method completes the Observable stream i.e., closes the stream.
Line 22: Observable has another method called subscribe which listens to the data
coming through the stream. Subscribe() method has three parameters. The first
parameter is a success callback which will be invoked upon receiving successful data
from the stream. The second parameter is an error callback which will be invoked
when Observable returns an error and the third parameter is a complete callback
which will be invoked upon successful streaming of values from Observable i.e.,
once complete() is invoked. After which the successful response, the data is pushed
to the local array called myArray, if any error occurs, a Boolean value called true is
stored in the errors variable and upon complete() will assign a Boolean value true in
a finished variable.

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

Following are the steps to run the Backend code :


• Download Backend code and run 'npm install' to download the packages as
shown below.
• Run the command 'node app' to start the node server as shown below.

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.

• Add the following code in book.service.ts file


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

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.

• Write the code given below in book.component.ts


1. import { Component, OnInit } from '@angular/core';
2. import { BookService } from './book.service';
3. import { Book } from './book';
4. @Component({
5. selector: 'app-book',
6. templateUrl: './book.component.html',
7. styleUrls: ['./book.component.css']
8. })
9. export class BookComponent implements OnInit {
10. title = 'Demo on HttpClientModule';
11. books!: Book[];
12. errorMessage!: string;
13. ADD_BOOK!: boolean;
14. UPDATE_BOOK!: boolean;
15. DELETE_BOOK!: boolean;
16. constructor(private bookService: BookService) { }
70 | P a g e S . S r i d h a r M E S G
17. getBooks() {
18. this.bookService.getBooks().subscribe({
19. next: books => this.books = books,
20. error:error => this.errorMessage = <any>error
21. })
22. }
23. addBook(bookId: string, name: string): void {
24. let id=parseInt(bookId)
25. this.bookService.addBook({id, name })
26. .subscribe({next:(book: any) =>
this.books.push(book)});
27. }
28. updateBook(bookId: string, name: string): void {
29. let id=parseInt(bookId)
30. this.bookService.updateBook({ id, name })
31. .subscribe({next:(book: any) => this.books = book});
32. }
33. deleteBook(bookId: string): void {
34. let id=parseInt(bookId)
35. this.bookService.deleteBook(id)
36. .subscribe({next:(book: any) => this.books = book});
37. }
38. ngOnInit() {
39. this.getBooks();
40. }
41. }
42.

• Write the code given below in book.component.html


1. <h2>{{ title }}</h2>
2. <h2>My Books</h2>
3. <ul class="books">
4. <li *ngFor="let book of books">
5. <span class="badge">{{ book.id }}</span> {{
book.name }}
71 | P a g e S . S r i d h a r M E S G
6. </li>
7. </ul>
8. <button class="btn btn-primary" (click)="ADD_BOOK
= true">Add Book</button>&nbsp;
9. <button class="btn btn-primary"
(click)="UPDATE_BOOK = true">Update Book</button>&nbsp;
10. <button class="btn btn-primary"
(click)="DELETE_BOOK = true">Delete Book</button>
11. <br />
12. <div *ngIf="ADD_BOOK">
13. <table>
14. <tr>
15. <td>Enter Id of the book:</td>
16. <td>
17. <input type="number" #id />
18. </td>
19. </tr>
20. <br />
21. <tr>
22. <td>Enter Name of the Book:</td>
23. <td>
24. <input type="text" #name />
25. <br />
26. </td>
27. </tr>
28. <br />
29. <tr>
30. <td>
31. <button class="btn btn-primary"
(click)="addBook(id.value, name.value); ADD_BOOK = false">
32. Add Record
33. </button>
34. </td>
35. </tr>
36. </table>
72 | P a g e S . S r i d h a r M E S G
37. <br />
38. </div>
39. <div *ngIf="UPDATE_BOOK">
40. <table>
41. <tr>
42. <td>Enter Id of the book:</td>
43. <td>
44. <input type="number" #id />
45. </td>
46. </tr>
47. <br />
48. <tr>
49. <td>Enter Name of the Book:</td>
50. <td>
51. <input type="text" #name />
52. <br />
53. </td>
54. </tr>
55. <br />
56. <tr>
57. <td>
58. <button class="btn btn-primary"
(click)="updateBook(id.value, name.value); UPDATE_BOOK = false">
59. Update Record
60. </button>
61. </td>
62. </tr>
63. </table>
64. </div>
65. <br />
66. <div *ngIf="DELETE_BOOK">
67. <table>
68. <tr>
69. <td>Enter Id of the book:</td>
70. <td>
73 | P a g e S . S r i d h a r M E S G
71. <input type="number" #id />
72. </td>
73. </tr>
74. <br />
75. <tr>
76. <td>
77. <button class="btn btn-primary"
(click)="deleteBook(id.value); DELETE_BOOK = false">
78. Delete Record
79. </button>
80. </td>
81. </tr>
82. </table>
83. </div>
84. <div class="error" *ngIf="errorMessage">{{
errorMessage }}</div>

• Save the files and check the output in the browser.

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

3. Open dashboard.component.ts and add the following code


1. import { BooksdataService } from './../book/booksdata.service';
2. import { Component, OnInit } from '@angular/core';
3. import { Router } from '@angular/router';
4. import { Book } from '../book/book';
5.
6. @Component({
7. selector: 'app-dashboard',
8. templateUrl: './dashboard.component.html',
9. styleUrls: ['./dashboard.component.css']
10.})
11.export class DashboardComponent implements OnInit {
12. books=this.book1Service.topBooks
13. constructor(
14. private router: Router,
15. private book1Service: BooksdataService) { }
16. ngOnInit(): void {
17. this.book1Service.getTopBooks()
18. }
19.}
20.

4. Open dashboard.component.html and add the following code


1. <h3>Top Books</h3>
76 | P a g e S . S r i d h a r M E S G
2. <div class="grid grid-pad">
3. <div *ngFor="let b of books" class="col-1-4">
4. <div class="module book">
5. <h4>{{ b. name}}</h4>
6. <span><a [routerLink]="['/detail', b.id]">Details</a></span>
7. </div>
8. </div>
9. </div>
10.

5. Open dashboard.component.css and add the following code


1. [class*="col-"] {
2. float: left;
3. }
4. *,
5. *:after,
6. *:before {
7. -webkit-box-sizing: border-box;
8. -moz-box-sizing: border-box;
9. box-sizing: border-box;
10.}
11.h3 {
12. text-align: center;
13. margin-bottom: 0;
14.}
15.[class*="col-"] {
16. padding-right: 20px;
17. padding-bottom: 20px;
18.}
19.[class*="col-"]:last-of-type {
20. padding-right: 0;
21.}
22..grid {
23. margin: 0;
24.}
77 | P a g e S . S r i d h a r M E S G
25..col-1-4 {
26. width: 25%;
27.}
28..module {
29. padding: 20px;
30. text-align: center;
31. color: #eee;
32. max-height: 120px;
33. min-width: 120px;
34. background-color: #607d8b;
35. border-radius: 2px;
36.}
37.h4 {
38. position: relative;
39.}
40..module:hover {
41. background-color: #eee;
42. cursor: pointer;
43. color: #607d8b;
44.}
45..grid-pad {
46. padding: 10px 0;
47.}
48..grid-pad > [class*="col-"]:last-of-type {
49. padding-right: 20px;
50.}
51.@media (max-width: 600px) {
52. .module {
53. font-size: 10px;
54. max-height: 75px;
55. }
56.}
57.@media (max-width: 1024px) {
58. .grid {
59. margin: 0;
78 | P a g e S . S r i d h a r M E S G
60. }
61. .module {
62. min-width: 60px;
63. }
64.}

6. Create another component called book-detail using the following command


1. D:\MyApp>ng generate component bookDetail

7. Open booksdata.service.ts and add getTopBooks() method as shown below to


fetch specific book details
1. import { Injectable } from '@angular/core';
2.
3. @Injectable({
4. providedIn: 'root'
5. })
6. export class BooksdataService {
7.
8. topBooks=[
9. {"id":1,"name":"HTML 5"},
10. {"id":2,"name":"CSS 3"},
11. {"id":3,"name":"Java Script"},
12. {"id":4,"name":"Ajax Programming"},
13. ]
14. books=[
15. {"id":1,"name":"HTML 5"},
16. {"id":2,"name":"CSS 3"},
17. {"id":3,"name":"Java Script"},
18. {"id":4,"name":"Ajax Programming"},
19. {"id":5,"name":"jQuery"},
20. {"id":6,"name":"Mastering Node.js"},
21. {"id":7,"name":"Angular JS 1.x"},
22. {"id":8,"name":"ng-book 2"},
23. {"id":9,"name":"Backbone JS"},
24. {"id":10,"name":"Yeoman"}
79 | P a g e S . S r i d h a r M E S G
25. ]
26. constructor() { }
27.
28. getTopBooks(){
29. return JSON.stringify(this.topBooks)
30. }
31.}

8. Open book-detail.component.ts and add the following code


1. import { Component, OnInit } from '@angular/core';
2. import { ActivatedRoute } from '@angular/router';
3. import { Book } from '../book/book';
4. import { BooksdataService } from '../book/booksdata.service';
5.
6. @Component({
7. selector: 'app-book-detail',
8. templateUrl: './book-detail.component.html',
9. styleUrls: ['./book-detail.component.css'],
10.})
11.export class BookDetailComponent implements OnInit {
12. constructor(private route:ActivatedRoute, private
bdetails:BooksdataService) { }
13. bookid:any;
14. book:any;
15. ngOnInit(): void {
16.
17. this.route.paramMap.subscribe(
18. params=>{
19. let n = params.get("id");
20. this.bookid=Number(n);
21. this.book=this.bdetails.topBooks.find(m=>m.id==this.bookid)
22. }
23. )
24. }
25.
80 | P a g e S . S r i d h a r M E S G
26. goBack() {
27. window.history.back();
28. }
29.}

9. Open book-detail.component.html and add the following code


1. <div *ngIf="book">
2. <h2>{{ book.name }} details!</h2>
3. <div><label>id: </label>{{ book.id }}</div>
4. <div>
5. <label>name: </label> <input [(ngModel)]="book.name"
placeholder="name" />
6. </div>
7. <button (click)="goBack()">Back</button>
8. </div>

10. Open book-detail.component.css and add the following code


1. label {
2. display: inline-block;
3. width: 3em;
4. margin: 0.5em 0;
5. color: #607d8b;
6. font-weight: bold;
7. }
8. input {
9. height: 2em;
10. font-size: 1em;
11. padding-left: 0.4em;
12.}
13.button {
14. margin-top: 20px;
15. font-family: Arial;
16. background-color: #eee;
17. border: none;
18. padding: 5px 10px;
81 | P a g e S . S r i d h a r M E S G
19. border-radius: 4px;
20. cursor: pointer;
21. cursor: hand;
22.}
23.button:hover {
24. background-color: #cfd8dc;
25.}
26.button:disabled {
27. background-color: #eee;
28. color: #ccc;
29. cursor: auto;
30.}
11. Generate PageNotFound component using the following CLI command
1. D:\MyApp>ng g c PageNotFound
12. Add below code to page-not-found.component.html:
1. <div>
2. <h1>404 Error</h1>
3. <h1>Page Not Found</h1>
4. </div>
13. Add the below code to app-routing.module.ts:
1. import { NgModule } from '@angular/core';
2. import { RouterModule, Routes } from '@angular/router';
3. import { BookComponent } from './book/book.component';
4. import { DashboardComponent } from './dashboard/dashboard.component';
5. import { BookDetailComponent } from './book-detail/book-
detail.component';
6. import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
7. const appRoutes: Routes = [
8. { path: 'dashboard', component: DashboardComponent },
9. { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
10. { path: 'books', component: BookComponent },
11. { path: 'detail/:id', component: BookDetailComponent },
12. { path: '**', component: PageNotFoundComponent },
13.];
82 | P a g e S . S r i d h a r M E S G
14.@NgModule({
15. imports: [
16. RouterModule.forRoot(appRoutes)
17. ],
18. exports: [
19. RouterModule
20. ]
21.})
22.export class AppRoutingModule { }

14. Write the below-given code in app.module.ts


1. import { BooksdataService } from './book/booksdata.service';
2. import { NgModule } from '@angular/core';
3. import { BrowserModule } from '@angular/platform-browser';
4. import { HttpClientModule } from '@angular/common/http';
5. import { FormsModule } from '@angular/forms';
6. import { AppComponent } from './app.component';
7. import { BookComponent } from './book/book.component';
8. import { DashboardComponent } from './dashboard/dashboard.component';
9. import { BookDetailComponent } from './book-detail/book-
detail.component';
10.import { AppRoutingModule } from './app-routing.module';
11.import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
12.
13.@NgModule({
14. imports: [BrowserModule, HttpClientModule, FormsModule,
AppRoutingModule],
15. declarations: [AppComponent, BookComponent, DashboardComponent,
BookDetailComponent, PageNotFoundComponent],
16. providers: [BooksdataService],
17. bootstrap: [AppComponent]
18.})
19.export class AppModule { }

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. }

16. Write the below-given code in app.component.html


1. <h1>{{title}}</h1>
2. <nav>
3. <a [routerLink]='["/dashboard"]'
routerLinkActive="active">Dashboard</a>
4. <a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
5. </nav>
6. <router-outlet></router-outlet>

17. Open app.component.css and add the following code


1. /* Master Styles */
2. h1 {
3. color: #369;
4. font-family: Arial, Helvetica, sans-serif;
5. font-size: 250%;
6. }
7. h2, h3 {
8. color: #444;
9. font-family: Arial, Helvetica, sans-serif;
10. font-weight: lighter;
11.}
12.body {
13. margin: 2em;
14.}
84 | P a g e S . S r i d h a r M E S G
15.body, input[text], button {
16. color: #888;
17. font-family: Cambria, Georgia;
18.}
19.a {
20. cursor: pointer;
21. cursor: hand;
22.}
23.button {
24. font-family: Arial;
25. background-color: #eee;
26. border: none;
27. padding: 5px 10px;
28. border-radius: 4px;
29. cursor: pointer;
30. cursor: hand;
31.}
32.button:hover {
33. background-color: #cfd8dc;
34.}
35.button:disabled {
36. background-color: #eee;
37. color: #aaa;
38. cursor: auto;
39.}
40.
41./* Navigation link styles */
42.nav a {
43. padding: 5px 10px;
44. text-decoration: none;
45. margin-right: 10px;
46. margin-top: 10px;
47. display: inline-block;
48. background-color: #eee;
49. border-radius: 4px;
85 | P a g e S . S r i d h a r M E S G
50.}
51.nav a:visited, a:link {
52. color: #607D8B;
53.}
54.nav a:hover {
55. color: #039be5;
56. background-color: #CFD8DC;
57.}
58.nav a.active {
59. color: #039be5;
60.}
61.
62./* everywhere else */
63.* {
64. font-family: Arial, Helvetica, sans-serif;
65.}

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.}

20. Open book.component.html and update with below code.


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>

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.

2. Add the following code to the login.component.ts file:


1. import { Component } from '@angular/core';
2. import { FormBuilder, FormGroup } from '@angular/forms';
3. import { Router } from '@angular/router';
4. import { LoginService } from './login.service';
89 | P a g e S . S r i d h a r M E S G
5. @Component({
6. templateUrl: './login.component.html',
7. styleUrls: ['./login.component.css'],
8. })
9. export class LoginComponent {
10. invalidCredentialMsg!: string;
11. loginForm!: FormGroup;
12. constructor(
13. private loginService: LoginService,
14. private router: Router,
15. private formbuilder: FormBuilder
16. ) {
17. this.loginForm = this.formbuilder.group({
18. username: [],
19. password: [],
20. });
21. }
22. onFormSubmit(): void {
23. const uname = this.loginForm.value.username;
24. const pwd = this.loginForm.value.password;
25. this.loginService
26. .isUserAuthenticated(uname, pwd)
27. .subscribe({next:(authenticated) => {
28. if (authenticated) {
29. this.router.navigate(['/books']);
30. } else {
31. this.invalidCredentialMsg = 'Invalid Credentials. Try again.';
32. }
33. }});
34. }
35.}

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.}

6. Add the following code in app.module.ts:


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';
92 | P a g e S . S r i d h a r M E S G
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, BookComponent,
DashboardComponent, BookDetailComponent, PageNotFoundComponent],
15. providers: [],
16. bootstrap: [AppComponent]
17.})
18.export class AppModule { }

7. Add the following code to app-routing.module.ts:


1. import { NgModule } from '@angular/core';
2. import { RouterModule, Routes } from '@angular/router';
3. import { BookComponent } from './book/book.component';
4. import { DashboardComponent } from './dashboard/dashboard.component';
5. import { BookDetailComponent } from './book-detail/book-
detail.component';
6. import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
7. import { authGuard } from './login/login-guard.service';
8. import { LoginComponent } from './login/login.component';
9. const appRoutes: Routes = [
10. { path: 'dashboard', component: DashboardComponent },
11. { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
12. { path: 'books', component: BookComponent , canActivate:[authGuard] },
13. { path: 'detail/:id', component: BookDetailComponent },
14. {path: 'login',component:LoginComponent},
15. { path: '**', component: PageNotFoundComponent },
16.];
17.@NgModule({
18. imports: [
19. RouterModule.forRoot(appRoutes)
93 | P a g e S . S r i d h a r M E S G
20. ],
21. exports: [
22. RouterModule
23. ]
24.})
25.export class AppRoutingModule { }

7. Save the files and check the output in the browser

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

1. ng g module book --routing

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 { }

4. Add the following code to the app-routing.module.ts file


1. import { NgModule } from '@angular/core';
2. import { RouterModule, Routes } from '@angular/router';
3. import { BookDetailComponent } from './book-detail/book-
detail.component';
4.
5. import { DashboardComponent } from './dashboard/dashboard.component';
6.
7. import { LoginComponent } from './login/login.component';
8. import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
9. const appRoutes: Routes = [
10. { path: '', redirectTo: '/login', pathMatch: 'full' },
11. { path: 'login', component: LoginComponent },
12. { path: 'books', loadChildren: () => import('./book/book.module').then(m
=> m.BookModule) },
13. { path: 'dashboard', component: DashboardComponent },
14. { path: 'detail/:id', component: BookDetailComponent} ,
15. { path: '**', component: PageNotFoundComponent }
16.];
17.@NgModule({
18. imports: [
19. RouterModule.forRoot(appRoutes)
20. ],
21. exports: [
22. RouterModule
23. ]
24.})
25.export class AppRoutingModule { }

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.

Run the backend folder provided in HTTP Client demo.

2. Write the following code in app.module.ts.


1. import { NgModule } from '@angular/core';
2. import { BrowserModule } from '@angular/platform-browser';
3. import { HttpClientModule } from '@angular/common/http';
4. import { ReactiveFormsModule } from '@angular/forms';
5. import { AppComponent } from './app.component';
6. import { AppRoutingModule } from './app-routing.module';
7. import { LoginComponent } from './login/login.component';
8. @NgModule({
9. imports: [BrowserModule, HttpClientModule, ReactiveFormsModule,
AppRoutingModule],
10. declarations: [AppComponent, LoginComponent],
11. providers: [],
12. bootstrap: [AppComponent]
13.})
14.export class AppModule { }

3. Write the following code in app-routing.module.ts.


1. import { NgModule } from '@angular/core';
2. import { RouterModule, Routes } from '@angular/router';
3. import { LoginComponent } from './login/login.component';
4. import { PageNotFoundComponent } from './page-not-found/page-not-
found.component';
5. const appRoutes: Routes = [
6. { path: '', redirectTo: '/login', pathMatch: 'full' },
7. { path: 'login', component: LoginComponent },
8. { path: 'books', loadChildren: () => import('./book/book.module').then(m
=> m.BookModule) },
9. { path: '**', component: PageNotFoundComponent }
10.];
99 | P a g e S . S r i d h a r M E S G
11.@NgModule({
12. imports: [
13. RouterModule.forRoot(appRoutes)
14. ],
15. exports: [
16. RouterModule
17. ]
18.})
19.export class AppRoutingModule { }

4. Write the following code in app.component.html


1. <h1>{{title}}</h1>
2. <nav>
3. <a [routerLink]='["/books"]' routerLinkActive="active">Books</a>
4. </nav>
5. <router-outlet></router-outlet>

5. Write the below code in book.module.ts


1. import { NgModule } from '@angular/core';
2. import { BookComponent } from './book.component';
3. import { BookRoutingModule } from './book-routing.module';
4. import { FormsModule } from '@angular/forms';
5. import { BookDetailComponent } from '../book-detail/book-
detail.component';
6. import { DashboardComponent } from '../dashboard/dashboard.component';
7. import { CommonModule } from '@angular/common';
8. @NgModule({
9. imports: [ CommonModule, BookRoutingModule, FormsModule],
10. declarations: [BookComponent, BookDetailComponent,
DashboardComponent]
11.})
12.export class BookModule { }

6. Write the following code in book-routing.module.ts.


1. import { NgModule } from '@angular/core';
100 | P a g e S . S r i d h a r M E S G
2. import { RouterModule, Routes } from '@angular/router';
3. import { BookComponent } from './book.component';
4. import { authGuard} from '../login/login-guard.service';
5. import { DashboardComponent } from '../dashboard/dashboard.component';
6. import { BookDetailComponent } from '../book-detail/book-
detail.component';
7. const bookRoutes: Routes = [
8. {
9. path: '',
10. component: BookComponent,
11. children: [
12. { path: 'dashboard', component: DashboardComponent },
13. { path: 'detail/:id', component: BookDetailComponent }
14. ],
15. canActivate: [authGuard]
16. }];
17.@NgModule({
18. imports: [RouterModule.forChild(bookRoutes)],
19. exports: [RouterModule]
20.})
21.export class BookRoutingModule { }

7. Write the below code in book.component.html


1. <br/>
2. <h2>MyBooks</h2>
3. <ul class="books">
4. <li *ngFor="let book of books " (click)="gotoDetail(book)">
5. <span class="badge">{{book.id}}</span> {{book.name}}
6. </li>
7. </ul>
8. <div>
9. <router-outlet></router-outlet>
10. </div>
11. <div class="error" *ngIf="errorMessage">{{errorMessage}}</div>

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.}

9. Update book-detail.component.html as below:


1. <div *ngIf="book">
2. <h2>{{ book.name }} details!</h2>
3. <div><label>id: </label>{{ book.id }}</div>
4. <div>
5. <label>name: </label> <input [(ngModel)]="book.name"
placeholder="name" />
102 | P a g e S . S r i d h a r M E S G
6. </div>
7. <button (click)="goBack()">Back</button>
8. </div>
9.

10.Update book-detail.component.ts as below:


1. import { Component, OnInit } from '@angular/core';
2. import { ActivatedRoute, Router } from '@angular/router';
3. import { Book } from '../book/book';
4. import { BooksdataService } from '../book/booksdata.service';
5.
6. @Component({
7. selector: 'app-book-detail',
8. templateUrl: './book-detail.component.html',
9. styleUrls: ['./book-detail.component.css'],
10.})
11.export class BookDetailComponent implements OnInit {
12. constructor(private route:ActivatedRoute, private
bdetails:BooksdataService, private r:Router) { }
13. bookid:any;
14. book:any;
15. ngOnInit(): void {
16.
17. this.route.paramMap.subscribe(
18. params=>{
19. let n = params.get("id");
20. this.bookid=Number(n);
21. this.book=this.bdetails.books.find(m=>m.id==this.bookid)
22. }
23. )
24. }
25.
26. goBack() {
27. this.r.navigate(['/books'])
28. }
103 | P a g e S . S r i d h a r M E S G
29.}

11.Save the files and check the output in the browser.

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

application, and reading the application data.


Perform CRUD Operations in MongoDB
Now that we know the components of the CRUD operation, let’s learn about
each individual operation in MongoDB. We will know what each operation
does, and the methods to perform these operations in MongoDB.
We will create, read, update and delete documents from MongoDB server.
1. Create Operations
The create or insert operations are used to insert or add new documents in
the collection. If a collection does not exist, then it will create a new collection
in the database.
You can perform, create operations using the following methods provided by
the MongoDB:
Method Description
It is used to insert a single document in
db.collection.insertOne()
the collection.
It is used to insert multiple documents in
db.collection.insertMany()
the collection.

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.

Performing CRUD Operations in MongoDB


Before we start exploring the CRUD methods. Let's first set up the db and
collection which we are going to use.
Creating a New Database:
To create a new database, you can simply run any command against a non-
existing database, and MongoDB will automatically create it for you.
Example:
Let us create a database name userdb.
use userdb;
Output:
switched to db userdb
Creating a New Collection:
To create a new collection, you can use the "createCollection" method.
Syntax:
db.createCollection(name, options)
Example:
db.createCollection("users")
Output:
{ "ok" : 1 }
Create Operation
There are two ways to create new documents to a collection in MongoDB:
1. insertOne():
Adding a single document to a collection is done using this method. A
document to be added is the only argument it accepts, and it returns a result
object with details about the insertion.
Syntax:
db.collectionName.insertOne()
Example:

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:

db.<collection>.createIndex(<Key and Index Type>, <Options>)


When creating an index, you need to define the field to be indexed and the
direction of the key (1 or -1) to indicate ascending or descending order.
Another thing to keep in mind is the index names. By default, MongoDB will
generate index names by concatenating the indexed keys with the direction of
each key in the index using an underscore as the separator. For example:
{name: 1} will be created as name_1.

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.

db.<collection>.dropIndex(<Index Name / Field Name>)


Let’s remove the user-created index with the index name student name index,
as shown below.

db.studentgrades.dropIndex("student name index")


Result:

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:

Common MongoDB index types


MongoDB provides different types of indexes that can be utilized according
to user needs. Here are the most common ones:
• Single field index
• Compound index
• Multikey index
Single field index
These user-defined indexes use a single field in a document to create an index
in an ascending or descending sort order (1 or -1). In a single field index, the
sort order of the index key does not have an impact because MongoDB can
traverse the index in either direction.

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.createIndex({subject: 1, score: -1})

In the above compound index, MongoDB will:


• First sort by the subject field
• Then, within each subject value, sort by grade
The index would create a data structure similar to the following:

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:

Now let’s create an index using the grades field.

120 | P a g e S . S r i d h a r M E S G
db.studentperformance.createIndex({grades:1})
Result:

The above code will automatically create a Multikey index in MongoDB.


When you query for a document using the array field (grades), MongoDB will
search for the first element of the array defined in the find() method and then
search for the whole matching query.
For instance, let’s consider the following find query:

db.studentperformance.find({grades: [80, 78, 71, 89]}, {_id: 0})


Initially, MongoDB will use the multikey index for searching documents
where the grades array contains the first element (80) in any position. Then,
within those selected documents, the documents with all the matching
elements will be selected.

Other MongoDB index types


In addition to the popular Index types mentioned above, MongoDB also offers
some special index types for targeted use cases:
• Geospatial index
• Test index
• Hashed index
Geospatial Index
MongoDB provides two types of indexes to increase the efficiency of database
queries when dealing with geospatial coordinate data:
• 2d indexes that use planar geometry which is intended for legacy coordinate
pairs used in MongoDB 2.2 and earlier.
• 2dsphere indexes that use spherical geometry.
121 | P a g e S . S r i d h a r M E S G
db.<collection>.createIndex( { <location Field> : "2dsphere" } )
Text index
The text index type enables you to search the string content in a collection.

db.<collection>.createIndex( { <Index Field>: "text" } )


Hashed index
MongoDB Hashed index type is used to provide support for hash-based
sharding functionality. This would index the hash value of the specified field.

db.<collection>.createIndex( { <Index Field> : "hashed" } )


MongoDB index properties
You can enhance the functionality of an index further by utilizing index
properties. In this section, you will get to know these commonly used index
properties:
• Sparse index
• Partial index
• Unique index
Sparse index
The MongoDB sparse property allows indexes to omit indexing documents in
a collection if the indexed field is unavailable in a document and create an
index containing only the documents which contain the indexed field.

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.

To switch to a different database, you can use the use command:


>use admin
switched to db admin
To get some basic information about your current database, you can use the db.stats()
method:

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

You might also like