You are on page 1of 153

Chapter 1 Typescript

Typescript is an object-oriented programming language developed and maintained by the


Microsoft Corporation. It is a superset of JavaScript and contains all of its elements and adds
optional static typing to the language. Typescript is designed for development of large
applications and trans compiles to JavaScript. TypeScript is a strongly typed language which can
be used to build web applications. It come with a special compiler that converts the strongly
typed language into JavaScript so it can run in a traditional browser. Since TypeScript is strongly
typed, it can offer better tooling around it than can be done with simple JavaScript.

Typescript totally follows the OOPS concept and with the help of TSC (Typescript Compiler), we
can convert Typescript code (.ts file) to JavaScript (.js file)

Typescript is a superset of JavaScript.

Why Should We Use TypeScript?

 TypeScript simplifies JavaScript code, making it easier to read and debug.


 TypeScript is open source.
 TypeScript provides highly productive development tools for JavaScript IDEs and
practices, like static checking.
 TypeScript makes code easier to read and understand.
 With TypeScript, we can make a huge improvement over plain JavaScript.
 TypeScript gives us all the benefits of ES6 (ECMAScript 6), plus more productivity.
 TypeScript can help us to avoid painful bugs that developers commonly run into when
writing JavaScript by type checking the code.
1
 Powerful type system, including generics.
 TypeScript is nothing but JavaScript with some additional features.
 Structural, rather than nominal.
 TypeScript code can be compiled as per ES5 and ES6 standards to support the latest
browser.
 Aligned with ECMAScript for compatibility.
 Starts and ends with JavaScript.
 Supports static typing.
 TypeScript will save developers time.
 TypeScript is a superset of ES3, ES5, and ES6.

Difference between TypeScript and JavaScript:


 TypesScript is known as Object oriented programming language whereas JavaScript is a
scripting language.
 TypeScript has a feature known as Static typing but JavaScript does not have this feature.
 TypeScript gives support for modules whereas JavaScript does not support modules.
 TypeScript has Interface but JavaScript does not have Interface.
 TypeScript support optional parameter function but JavaScript does not support optional
parameter function.

Advantages of using TypeScript over JavaScript


 TypeScript always point out the compilation errors at the time of development only.
Because of this at the run-time the chance of getting errors are very less whereas JavaScript
is an interpreted language.
 TypeScript has a feature which is strongly-typed or supports static typing. That means Static
typing allows for checking type correctness at compile time. This is not available in
JavaScript.
 TypeScript is nothing but JavaScript and some additional features i.e. ES6 features. It may
not be supported in your target browser but TypeScript compiler can compile the .ts files
into ES3,ES4 and ES5 also.

2
Environment Setup

To get started with TypeScript installation, you need to first install Node.js in your system. The
installer comes with Node and npm, where npm is the package manager for JavaScript. It consists
of a command line client and an online database, called npm registry, which contains public and
paid-for private packages.

Node.js Installation

To begin with Node.js installation, head over to https://nodejs.org/en/ in your browser window,
where you will see a page like the following one. The installer under the LTS tab is recommended
for most of the users, whereas the installer under the Current tab is the latest version of Node.
Let's download the latest version, which is 10.0.0 in our case.

Once downloaded, double-click on the installer file and follow the step-by-step process to install
the Node.js in your computer. Make sure that the Node.js runtime, npm package manager, and

3
Add to PATH are selected for installation. You will need administrative privileges on your system
to complete the installation.

Now open any Console Window (cmd.exe) and type the following command, node -v, to confirm
whether the installation was successful. This will return the installed version number in the
console output, which is v10.0.0 in our case. If everything looks good, proceed with the next
point to install TypeScript.

To verify the installation was successful, enter the following command in the Terminal Window.

1. $ node -v
2. $ npm -v

TypeScript Installation

As you have already installed Node, it's time to install the TypeScript Package using the Node
Package Manager (NPM). To begin with the installation, open any Console Window ( cmd.exe)
and enter the following command in the prompt:

npm install -g typescript

This will download the latest version from the server, extract it and install on your system. A
progress indicator will be shown, marking the current progress of the installation. Here's the
screenshot of the final output, for your reference:

4
Once you are done with the installation, type tsc in the command prompt and hit Enter. This will
list the TypeScript Compiler Usages on the console window.

TypeScript Installation Using Visual Studio

If you are using Visual Studio, you can simply install it to your Visual Studio IDE from the Visual
Studio installer. Run the installer and click Modify to customize the installation components.
Navigate to the Individual components tab and select the desired version of TypeScript SDK that
you want to install. Click Modify to perform the installation:

Once installed, you can check the TypeScript version using the following command:

> tsc -v

INSTALL
npm install -g typescript
COMPILE
tsc helloworld.ts

5
− To compile the file use the following command on the terminal window.

tsc Test.ts

The file is compiled to Test.js. To run the program written, type the following in the terminal.

node Test.js

Text Editors With TypeScript Support

TypeScript is an open-source project but it is developed and maintained by Microsoft Inc. and it
was initially supported only in Microsoft’s Visual Studio platform. Nowadays, there are lots of
text editors and IDEs that either natively or through plugins have support for the TypeScript
syntax, auto-complete suggestions, error catching, and even built-in compilers.

Step-1 Open the Text Editor and write/copy the following code.

Create a new file in your code editor and name it "add.ts". Write the following code in it:

File: add.ts

function addNumbers(a: number, b: number) {


return a + b;
}
var sum: number = addNumbers(10,15)
console.log('Sum of the two numbers is: ' +sum);

Save the above file as ".ts" extension.


Now, open the command prompt on Windows (or a terminal in your platform), navigate to the
path where you saved add.ts and compile the above TypeScript program in your terminal using
the following command:

> tsc add.ts

6
For example, if we save the file on the desktop, go to the terminal window and type: - cd
Desktop/folder_name. Now, type the following command tsc filename.ts for compilation and
press Enter.

NOTE: If we directly run ".ts" file on the web browser, it will throw an error message. But after
the compilation of ".ts" file, we will get a ".js" file, which can be executed on any browser.

Datatypes In TypeScript

1. Number – All the numeric values are represented by a number type, there aren’t separate
definitions for integers, floats or others.
2. String – The text type datatype, just like in vanilla JS strings can be surrounded by ‘single
quotes’ or “double quotes.”
3. Boolean – It is either true or false, using 0 and 1 will cause the compilation error.
4. Any – A variable with this type can its value set to the string, number, or anything else.
5. Arrays – Has two possible syntaxes: my_arr: number[] or my_arr: Array<number>.
6. Void – Used on the function that doesn’t return anything.

TypeScript – Variable

Variable is a named place in memory where some data/value can be stored.

While declaring a variable, some rules have to be followed:

 Variable names can contains alphabets both Upper-case as well as Lower-case and digits
also.
 Variable name cant start with digit.
 We can use _ and $ special character only, apart from these other special characters are
not allowed.
Variable declaration: We can declare a variable in multiple ways like below:
var Identifier:Data-type = value;
var Identifier: Data-type;

7
var Identifier = value;
var Identifier;

TypeScript follows the same rules as JavaScript for variable declarations. Variables can be
declared using: var, let, and const.

var Declaration

Variables in TypeScript can be declared using var keyword, same as in JavaScript. The scoping
rules remains the same as in JavaScript.

let Declaration

To solve problems with var declarations, ES6 introduced two new types of variable declarations
in JavaScript, using the keywords let and const. TypeScript, being a superset of JavaScript, also
supports these new types of variable declarations.

Example: let employeeName = "John";

let employeeName:string = "John";

Const Declaration

Variables can be declared using const similar to var or let declarations. The const makes a variable
a constant where its value cannot be changed. Const variables have the same scoping rules as let
variables. Const works almost the same as let. However, the only difference is that once you’ve
assigned a value to a const variable, you can’t reassign it to a new value.

Example: Const Variable

const num:number = 100;

num = 200; //Com

Variable scopes in Typescript: Here scope means the visibility of variable. The scope defines that
we are able to access the variable or not. TypeScript variables can be of the following scopes:
 Local Scope: As the name specified, are declared within the block like methods, loops etc.
Local variables are accessible only within the construct where they are declared.

8
 Global Scope: If the variable is declared outside the construct then we can access the
variable anywhere. This is known as Global Scope.
 Class Scope: If a variable is declared inside the class then we can access that variable within
the class only.

TypeScript Operators

An Operator is a symbol which operates on a value or data. It represents a specific action on


working with data. The data on which operators operates is called operand. It can be used with
one or more than one values to produce a single value. All of the standard JavaScript operators
are available with the TypeScript program.

Arithmetic Operators: - Arithmetic operators take numeric values as their operands, performs
an action, and then returns a single numeric value. The most common arithmetic operators are
addition(+), subtraction(-), multiplication(*), and division(/).

Operator Operator_Name Description Example

+ Addition It returns an addition of the let a = 20; let b = 30; let c = a + b;


values. console.log( c ); //
Output 30

- Subtraction It returns the difference of let a = 30;let b = 20;let c = a - b;


the values. console.log( c ); //
Output 10

* Multiplication It returns the product of let a = 30;let b = 20; let c = a * b;


the values. console.log( c ); Output
600

9
Division It performs the division let a = 100;let b = 20;let c = a / b;
operation, and returns the console.log( c );
quotient. Output 5

% Modulus It performs the division let a = 95;let b = 20;let c = a % b;


operation and returns the console.log( c );
remainder. Output 15

++ Increment It is used to increments let a = 55;


the value of the variable a++;
by one. console.log( a );
Output 56

-- Decrement It is used to decrements let a = 55;


the value of the variable a--;
by one. console.log( a );
Output 54

Comparison (Relational) Operators:- The comparison operators are used to compares the two
operands. These operators return a Boolean value true or false. The important comparison
operators are given below.

Operator Operator_Name Description Example

== Is equal to It checks whether the let a = 10; let b = 20;


values of the two console.log(a==b); //false
operands are equal or console.log(a==10); //true
not. console.log(10=='10'); //true

10
=== Identical(equal It checks whether the let a = 10; let b = 20;
and of the same type and values of the console.log(a===b); //false
type) two operands are equal console.log(a===10); //true
or not. console.log(10==='10'); //false

!= Not equal to It checks whether the let a = 10; let b = 20;


values of the two console.log(a!=b); //true
operands are equal or console.log(a!=10); //false
not. console.log(10!='10'); //false

!== Not identical It checks whether the let a = 10;let b = 20;


type and values of the console.log(a!==b); //true
two operands are equal console.log(a!==10); /false
or not. console.log(10!=='10'); //true

> Greater than It checks whether the value let a = 30; let b = 20;
of the left operands is console.log(a>b); //true
greater than the value of the console.log(a>30); //false
right operand or not. console.log(20> 20'); //false

>= Greater than or It checks whether the value let a = 20; let b = 20;
equal to of the left operands is console.log(a>=b); //true
greater than or equal to the console.log(a>=30); //false
value of the right operand console.log(20>='20'); //true
or not.

< Less than It checks whether the value let a = 10; let b = 20;
of the left operands is less console.log(a<b); //true
than the value of the right console.log(a<10); //false
operand or not. console.log(10<'10'); //false

11
<= Less than or equal It checks whether the value let a = 10; let b = 20;
to of the left operands is less console.log(a<=b); //true
than or equal to the value of console.log(a<=10); //true
the right operand or not. console.log(10<='10'); //true

Logical Operators :- Logical operators are used for combining two or more condition into a single
expression and return the Boolean result true or false.

Operator Operator_Name Description Example

&& Logical AND It returns true if both the let a = false; let b = true;
operands(expression) are true, console.log(a&&b); /false
otherwise returns false. console.log(b&&true); //true
console.log(b&&10); //10
which is also 'true'
console.log(a&&'10'); //false

|| Logical OR It returns true if any of the let a = false; let b = true;


operands(expression) are true, console.log(a||b); //true
otherwise returns false. console.log(b||true); //true
console.log(b||10); //true
console.log(a||'10'); //'10'
which is also 'true'

Bitwise Operators :-

12
Operator Operator_Name Description Example

& Bitwise AND It returns the result of a let a = 2;let b = 3;


Boolean AND operation on let c = a & b;
each bit of its integer console.log(c);
arguments. Output 2

| Bitwise OR It returns the result of a let a = 2;let b = 3;


Boolean OR operation on let c = a | b;
each bit of its integer console.log(c);
arguments. Output 3

^ Bitwise XOR It returns the result of a let a = 2;let b = 3;


Boolean Exclusive OR let c = a ^ b;
operation on each bit of console.log(c); Output 1
its integer arguments.

~ Bitwise NOT It inverts each bit in the let a = 2;let c = ~ a;


operands. console.log(c); //
Output -3

>> Bitwise Right The left operand's value is let a = 2;let b = 3;let c = a >>
Shift moved to the right by the b;
number of bits specified in console.log(c); //
the right operand. Output 0

13
<< Bitwise Left The left operand's value let a = 2;
Shift is moved to the left by let b = 3;
the number of bits let c = a << b;
specified in the right console.log(c); //
operand. New bits are Output 16
filled with zeroes on the
right side.

Assignment Operators :- Assignment operators are used to assign a value to the variable. The
left side of the assignment operator is called a variable, and the right side of the assignment
operator is called a value. The data-type of the variable and value must be the same otherwise
the compiler will throw an error. The assignment operators are as follows.

Operator Operator_Name Description Example

= Assign It assigns values from right side to let a = 10;


left side operand. let b = 5;
console.log("a=b:"
+a); //
Output
10

+= Add and assign It adds the left operand with the let a = 10;
right operand and assigns the let b = 5;
result to the left side operand. let c = a += b;
console.log(c); //
Output
15

14
-= Subtract and It subtracts the right operand from let a = 10;
assign the left operand and assigns the let b = 5;
result to the left side operand. let c = a -= b;
console.log(c); //
Output
5

*= Multiply and It multiplies the left operand with let a = 10;


assign the right operand and assigns the let b = 5;
result to the left side operand. let c = a *= b;
console.log(c); //
Output
50

/= Divide and It divides the left operand with the let a = 10;
assign right operand and assigns the let b = 5;
result to the left side operand. let c = a /= b;
console.log(c); //
Output
2

%= Modulus and It divides the left operand with the let a = 16;
assign right operand and assigns the let b = 5;
result to the left side operand. let c = a %= b;
console.log(c); //
Output
1

15
Ternary/Conditional Operator :- The conditional operator takes three operands and returns a
Boolean value based on the condition, whether it is true or false. Its working is similar to an if-
else statement. The conditional operator has right-to-left associativity. The syntax of a
conditional operator is given below.

1. expression ? expression-1 : expression-2;

o expression: It refers to the conditional expression.

o expression-1: If the condition is true, expression-1 will be returned.

o expression-2: If the condition is false, expression-2 will be returned.

e.g let num = 16;


let result = (num > 0) ? "True":"False"
console.log(result);

Output: True

Concatenation Operator :- The concatenation (+) operator is an operator which is used to append
the two string. In concatenation operation, we cannot add a space between the strings. We can
concatenate multiple strings in a single statement. The following example helps us to understand
the concatenation operator in TypeScript.

TypeScript Arrow function

ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining
the anonymous function, i.e., for function expressions. It omits the function keyword. We can
call it fat arrow (because -> is a thin arrow and => is a "fat" arrow). It is also called a Lambda
function. The arrow function has lexical scoping of "this" keyword.

The motivation for arrow function is:

o When we don't need to keep typing function.

o It lexically captures the meaning of this keyword.

16
o It lexically captures the meaning of arguments.

Syntax : We can split the syntax of an Arrow function into three parts:

o Parameters: A function may or may not have parameters.

o The arrow notation/lambda notation (=>)

o Statements: It represents the function's instruction set.

1. (parameter1, parameter2, ..., parameterN) => expression;

If we use the fat arrow (=>) notation, there is no need to use the function keyword. Parameters
are passed in the brackets (), and the function expression is enclosed within the curly brackets {}.

There are two ways of writing a function in ES5 and ES6 style of coding.

// ES5: Without arrow function


var getResult = function(username, points) {
return username + ' scored ' + points + ' points!';
};
// ES6: With arrow function
var getResult = (username: string, points: number): string => {
return `${ username } scored ${ points } points!`;
}

TypeScript is object oriented JavaScript. TypeScript supports object-oriented programming


features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A
class encapsulates data for the object. Typescript gives built in support for this concept called
class. JavaScript ES5 or earlier didn’t support classes. Typescript gets this feature from ES6.

Creating classes

Use the class keyword to declare a class in TypeScript. The syntax for the same is given below −

Syntax: class class_name {

17
//class scope
}

The class keyword is followed by the class name. The rules for identifiers must be considered
while naming a class.

A class definition can include the following −

 Fields − A field is any variable declared in a class. Fields represent data pertaining to
objects

 Constructors − Responsible for allocating memory for the objects of the class

 Functions − Functions represent actions an object can take. They are also at times
referred to as methods

These components put together are termed as the data members of the class.

Consider a class Person in typescript.

class Person {
}

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10


var Person = (function () {
function Person() {
}
return Person;
}());

Inheritance is an aspect of OOPs languages, which provides the ability of a program to create
a new class from an existing class. It is a mechanism which acquires
the properties and behaviors of a class from another class. The class whose members are
inherited is called the base class, and the class that inherits those members is called

18
the derived/child/subclass. In child class, we can override or modify the behaviors of its
parent class. Syntax

class sub_class_name extends super_class_name


{
// methods and fields
{

Why use inheritance?


o We can use it for Method Overriding (so runtime polymorphism can be achieved).
o We can use it for Code Reusability.

Types of Inheritance

We can classify the inheritance into the five types. These are:

o Single Inheritance
o Multilevel Inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

19
Single Inheritance: Single inheritance can inherit properties and behavior from at most one
parent class. It allows a derived/subclass to inherit the properties and behavior of a base class
that enable the code reusability as well as we can add new features to the existing code.

Multilevel Inheritance: When a derived class is derived from another derived class, then this type
of inheritance is known as multilevel inheritance. Thus, a multilevel inheritance has more than
one parent class. It is similar to the relation between Grandfather, Father, and Child.

Multiple Inheritance: When an object or class inherits the characteristics and features form
more than one parent class, then this type of inheritance is known as multiple inheritance. Thus,
a multiple inheritance acquires the properties from more than one parent class. TypeScript does
not support multiple inheritance.

Hierarchical Inheritance: When more than one subclass is inherited from a single base class, then
this type of inheritance is known as hierarchical inheritance. Here, all features which are
common in sub-classes are included in the base class. TypeScript does not support hierarchical
inheritance.

Hybrid Inheritance: When a class inherits the characteristics and features from more than
one form of inheritance, then this type of inheritance is known as Hybrid inheritance. In other
words, it is a combination of multilevel and multiple inheritance. We can implement it by
combining more than one type of inheritance. TypeScript does not support hybrid inheritance.

20
Chapter 2 Angular

What is Angular 8

Angular is a Framework of JavaScript used to build web and mobile applications. Angular 8 is a
client-side TypeScript based structure which is used to create dynamic web applications. Its first
version was released by Google in 2012 and named as AngularJS. Angular 8 is the updated
version of Angular 2.
Before starting Angular, we must have a good understanding of JavaScript, HTML, CSS and
TypeScript.
Angular 8 is a great UI (User Interface) library for the developers. Angular is a reusable UI
component helps us constructing attractive, consistent, and functional web pages and web
application. Angular 8 is a JavaScript framework which makes us able to create an
attractive Single Page Applications (SPAs).
“A single page application is a web application or a website which provides a fluid, reactive, and
fast application same as a desktop application. It contains menu, buttons, and blocks on a single
page and when a user clicks on them, it dynamically rewrites the current page without loading
new pages from the server so that its speed is fast.”

Angular 8 has entirely based on component and consist of some tree structures with parent and
child component. Angular 8 classes are created in such a way that the web page can fit in any
screen size so that they are fully compatible with mobiles, tablets, laptops, and large systems.

Angular Versions

Version Released

Angular JS October 2010

Angular2.0 September 2016

21
Angular4.0 March 2017

Angular5.0 November 2017

Angular6.0 May 2018

Angular 8.0 October 2018

The release dates of major two upcoming versions of Angular are following:

Version Released

Angular 8.0 March/April 2019

Angular9.0 September/October 2019

Google plans to release the significant Angular version every six months.

How to update Angular to Angular 8?

Angular 8 is the major release in the Angular core framework, Angular CLI, Angular Materials are
updated. If we are using Angular 5 or 6 and want to update to Angular 8, below is the command
which will update our app to the recent version of angular.

ng update @angular/cli @angular/core

CLI Workflow Improvements

The Angular CLI is continuously improving, and now the ng-build, ng-test and ng-run are equipped
to be extended by 3rd party libraries and tool.
Builders API:
The new version allows us to use builders API. It uses builders for mail operations like Serve, build,
test, link, and e2e and now we can create our custom builders as well.

22
Improvements in $location service:
$location service helps you to retrieve the state from location service, track all location changes,
and retrieve protocol port search properties.

Service Worker:
It helps increased reliability and performance without needing to code against low-level APIs and
can achieve native-like application download and installation.

Difference between Angular Js and Angular

Angular JS Angular

Angular JS is a JavaScript-based open- Angular is a typescript based full-stack web application


source front end web development. framework.

Angular JS uses the concept of scope or Angular uses the hierarchy of components in place of
controller. scope and controllers.

Angular JS does not support dynamic


Angular supports dynamic loading of the page.
loading of the page.

Angular JS has simple syntax and used Angular uses different expression syntax uses “[ ]” for
on HTML pages. property binding and “( )” event binding.

Angular JS is a simple JavaScript file,


It uses Typescript language which provides class-based
used with HTML pages, and does not
object-oriented programming languages and support
support the features of server site
features of server site programming language.
programming languages.

23
Angular Keywords

What is Angular CDK?

The Component Dev Kit (CDK) is a set of tools that implement common interaction patterns
while being preserve about their presentation. It represents an abstraction of the core
functionalities found in the Angular Material library, without any styling specifically to Material
Design.
What is Angular CLI?

Angular CLI is known as Angular Command Line Interface. It is a command-line tool for creating
angular apps. It is mentioned to use angular CLI for creating angular apps as if we do not need to
spend time to install and configure all the required dependencies and wiring everything
together. Angular CLI is a helpful tool to create and work with Angular Applications efficiently.

What is Ng in Angular?

The prefix ng stands for “Angular;” all of the built-in directives that craft with Angular use that
prefix. Similarly, it is suggested that you do not use the ng prefix on your instructions to avoid
possible name impacts in future versions of Angular.

Installation Guides to Angular 8 step by Step


Angular combines declarative templates, dependency injection and, end to end tooling to solve
development challenges. Angular empowers developers to build an application that lives on the
mobile, web, and the desktop. The current version of Angular is 7.2.13, and we are going to
explain the steps of installation in Windows 10 operating system.

To install Angular 8, we require the following things:


 Windows 10

24
 Node.js (12.6.0)

 NPM

 Angular CLI(Command Line Interface)

 An IDE for writing our code(VS code)

 Git

 1. Install Node.js:Firstly, we need to install node.js in our system then NPM will be
connected with node.js. So, the latest version of node.js could be downloaded and
installed from the official website. Currently, 12.4.0 is the trending version of node.js. The
URL is given below:
 https://nodejs.org
 After opening the link, this page has appeared. We can choose the second one for latest
version of node and npm.

 After downloading, we have to install the node.js in our system. The steps are as follows:

25
Click on “Run.”and Next

Click “Next.”

26
 Again click “Next.”

 Click on “Install.”

27

 The node.js is successfully installed in our system.


 Installation of Git
 Firstly, we have to open the official website of Git:
 https://gitforwindows.org

28
 Click on “Run.”

 Click on “Next.”

29

30
 In the above screenshot, the Git is successfully installed in our system.
 After that, we have to install AngularCLI in our system so that we have to open the official
website of angular form the URL:
 https://cli.angular.io
 We can check the current version of Node and Node package manager (Npm) from the
following command Node –v
 Npm -v
 Right-click on the desktop and click on “Git Bash Here” then a command-line interface
will open in the desktop.

 Here, the “GIT BASH” is opened in our system,and thenwrite the commands.

31
 And then we have to download the Angular CLI with the help of command-line
in Git. Write this command in Git Bash

npm install&nbsp; –g @angular/cli


or
npmi –g @angular/cli

To install the Angular CLI, We have to write the following command in Git.

npm install –g @angular/cli


 It will successfully installed in our system according to the following screenshot.

 Our Angular 8 set-up is complete now.

32
Creating first APP in Angular 8
ng new my -app

Then, we have to run this project in the server and launch through this command.

33
cd project name

ng serve --open

After that, the default local host has been automatically created and opens in our system from
Local host 4200.

After creating the project, we want an IDE to open and edit the code to do the project so that we
are downloading the VS code in our system through its website.

34
After downloading we have to install VS code.

Click on “Next”.

Again, click on “Next”.

35
Click on “Next”.

After downloading and installing the VS code in our system, we can open our project in it.
36
After that, we will open our project in the VS code.

Here, we can add and edit our code in VS Code to do our project, and all our libraries and files
are there to the system.

Our project is generated now.


If our project is completed then, we have to build this project to uploading its whole files on the
server.To create the plan, we have to use this command in GIT, which is given as follow:

ng build

37
It will build successfully according to the above screenshot.
We can also check it directly through the file.

Just go and click on the project file after that go to the “dist” folder and then open the project
click on the name after that the data will be seen to us. If we want to upload, then we have to

38
upload all the files in the server which are there in the folder according to a screenshot given
below.

These are the files which are built.

We can also see the change in VS code after building the project which is given below:

39
For verifying the version of Angular CLI installed: ng -v

Difference between Angular and React

40
Parameters Angular React

React is a JavaScript library,


Type Angular is a complete framework. and much older compared to
Angular.

React JS can be packaged with


Use of Library Angular is a complete solution itself. another programming
libraries.

It has dependable community It doesn’t offer much in


Community support
support. community support.

React takes longer to set up.


Angular is easy to set up, but it may
Installation time But, it is fast for delivering
lead to an increase in coding time.
projects and building apps.

React gives us the freedom to


It offers a limited amount of choose the tools, architecture,
Feature
freedom and flexibility. and libraries, for developing
an app.

Angular uses two-way data binding React language uses one-way


method. It helps you to ensure that data binding, which elements
Data binding
the model state automatically cannot be changed without
changes when any change is made. updating the model.

41
In Angular, The testing and It requires a set of tools to
Testing and
debugging of a whole project is perform various types of
debugging
possible with a single tool. testing.

Due to the ongoing development


The documentation is faster
Documentation process, the documentation is
here.
slower.

Updates in React are simple


Updates It updates itself every six months.
because it helps in migration.

If we want to develop a SPA (Single We use to react when we want


Application Types Page Application) and the mobile to develop Native apps, hybrid
app, then Angular is best. apps, or web apps.

Based on MVC (Model View It is mainly based on virtual


Model
Controller) DOM

Written in Typescript JavaScript

Facebook developer’s
Community support A large community of developers.
community.

Language
Typescript JSX- JavaScript XML
Preferences

42
Facebook, Uber technologies,
We pay, Beam, Auto trader, Mesh,
Companies using Instagram, Netflix, Pinterest,
Streamline social, etc.
Etc

Template HTML+ Typescript JSX+ J% (ES5/ES6)

Adding JavaScript
Adding JavaScript library to the Adding JavaScript library to
library to the source
source code is not possible. the source code is possible.
code

Angular has a lot of ready to use


elements. However, it mainly comes React allows us to manage
Use of code from a specific provider. So, there code according to our desired
are priority collisions and format.
namespaces.

Both React JS and Angular JS are great options for single page application and both of them are
entirely different instruments. May be our perception about React Vs Angular JS, is based on our,
requirement of functionality and usability.

Advantages of Angular 8
 It offers clean code development

 Higher Performance

 An angular framework can take care of routing, which means moving from one view to
another is easy in Angular.

 Seamless updates using Angular CLI (Command Line Interface).

 It allows the ability to retrieve the state of location services.

43
 We can debug templates in angular 8.

 It supports multiple apps in one domain.

File Structure in Angular 8


A file structure contains the files for one or more projects. A project is the set of files that
comprise an application on a shareable library. An angular module is used to group related
angular components, services, directives, etc.

Let see the structure of the Angular 8 app on VS code IDE for Angular development, and we can
use either Web Storm IDE or Visual Studio IDE. Both are better. Here, we are using the VScode
IDE.

44
Files used in Angular 8 app folder

Angular 8 app files which are used in our project are below:

 Src folder: It is the folder which contains the main code files related to our angular
application.
 app folder: It contains the files which we have created for app components.
 app.component.css: The file contains the CSS(cascading style sheets) code in our app
component.
 app.component.html: The file contains the HTML file related to its app component. Itis
the template file which is specially used by angular to the data binding.
 app.component.spec.ts: This file is a unit testing file is related to the app component.
This file is used across with more other unit tests. It is run from angular CLI by command
ng test.
 app.component.ts: It is the essential typescript file which includes the view logic beyond
the component.
 app.module.ts: It is also a typescript file which consists of all dependencies for the
website. The data is used to define the needed modules has been imported, the
components to be declared, and the main element to be bootstrapped.
Other Important Files in Angular 8

 package.json: It is the npm configuration file. It includes details of our website’s and
package dependencies with more information about our site being a package itself.
 package-lock.json: This is an auto-generated and transforms file that gets updated when
npm does an operation related to the node_modules or package.json file.
 angular.json:It is a necessary configuration file related to our angular application. It
defines the structure of our app and includes any setting to accomplish with the
application.
 .gitignore: The record is related to the source code git.

45
 .editorconfig: This is a standard file which is used to maintain consistency in code editors
to organizing some basics. such as indentation and whitespaces.
 Assets folder: This folder is a placeholder for the resource files which are used in the
application such as images, locales, translations, etc.
 Environment folder: The environment folder is used to grasp the environment
configuration constants that help when we are building the angular application.
 Browser list: This file specifies a small icon that appears next to the browser tab of a
website.
 favicon.ico:It defines a small image that appears next to the browser tab of any website.
 Index.html: It is the entry file which holds the high-level container for the angular
application.
 karma.config.js: It specifies the config file in the karma Test runner, Karma has been
developed by the AngularJS team and can run tests for AngularJS and Angular 2+.
 main.ts: This is the main ts file that will run; first, It is mainly used to define the global
configurations.
 polyfills.ts: The record is a set of code that can be used to provide compatibility support
for older browsers. Angular 8 code is written in ES6+ specifications.
 test.ts:It is the primary test file that the Angular CLI command ng test will apply to
traverse all the unit tests within the application.
 styles.css: It is the angular application uses a global CSS.
 tsconfig.json:This is a typescript compiler of the configuration file.
 tsconfig.app.json: It is used to override the ts.config.json file with app-specific
configurations.
 tsconfig.spec.json: It overrides the tsconfig.json file with the app-specific unit test cases.

Angular 8 Components
Angular is used for building mobile and desktop web applications. The component is the basic
building block of Angular. It has a selector, template, style, and other properties, and it specifies
the metadata required to process the component.

46
Components are defined using a @component decorator and a tree of the angular component.
It makes our complex application in reusable parts which we can reuse easily.
The component is the most critical concept in Angular and a tree of components with a root
component. The root component is one contained in the bootstrap array in the
main ngModule module defined in the app.module.ts file.

What is Component-Based Architecture?

An Angular application is build of some components which form a tree structure with parent and
child components. A component is an independent block of an extensive system that
communicates with the other building blocks of the systems using inputs and outputs. It has an
associated view, data, and behavior and has parent and child components.

The component allows maximum re-usability, secure testing, maintenance, and separation of
concerns. Go to our Angular project folder and open the src/app folder, which we will see the
following files.

App folder: The app folder contains the data we have created for app components.
 app.component.css: The component CSS file.
 app.component.html: This component is used for HTML view.
 app.component.spec.ts: The HTML view of the component
 app.component.ts: Component code (data and behavior)
 app.module.ts: The main application module.

47
Go further and open the src/app/app.component.ts file and let’s understand the code behind
the root component of the application.
Import { Component } from ‘@angular/core’;

@Component ({

Selector: ‘app-root’,

templateUrl: ‘./app.component.html’ ,

styleUrls: [‘./app.component.css’]

})

export class AppComponent {

title = ‘myfirstapp’;

48
Firstly, we import the Component decorator from @angular/core and then we use it to preserve
the Typescript AppComponent class. The Component decorator takes an object with multiple
parameters, however:
 selector: It specifies the tag that can be used to call this component in HTML templates
just like the standard HTML tags
 templateUrl: It indicates the path of the HTML template that will be used to display this
component.
 styleUrls: It specifies an array of URLs for CSS style-sheet in the component.

The export keyboard is used to export the component, and it has imported from other
components and modules in the application file.

The title variable is a member variable which holds the string’ app,’ and it is not the part of the
legal definition of any Angular component.

Let’s see the corresponding template for that component. If we open src/app.component.html

49
The template is an HTML file is used inside an HTML template except for the following tags
<script>, <html>, and <body> with the exception that it contains template variable or expression
and it can be used to insert values in DOM automatically. It is called interpolation and data
binding.

How to create a new Component?

This is the basic building block of Angular.

Open VS code then go to your project source folder then expand the app directory and create a
new list named ‘server.’
Now, create a component in the server directory. Right-click on server directory and create a new
file named as ‘server.component.ts.’ It is the recently created component.

Components are used to build webpages in all versions of Angular, but they require modules to
bundle them together. Now, we have to register our new component in the module.

50
Creating a component with CLI

ng generate component component_name

Or

ng g c Component-name

Let’s see how to create an element in the command line.

Open the command prompt and stop ng serve Command if it is running on the browser. Type ng
generate component server (where the server is the name of the component we are created to
create a new component named server2).

We can also use a shortcut commandng g c server for the same task. Firstly, we have to open our
Project with cd myfirstapp and then create the component server2.

51
In the above screenshot, we see that a new component named “server2” is created. It contains
various files:-

server2.component.css

server2.component.html

server2.component.spec.ts

server2.component.ts

server2.component.spec.ts is usually used for testing purpose. We can delete it by clicking right
on it.

52
Routing in Angular 8

Angular Router is a powerful JavaScript router is built and maintained by the Angular core team
that can install from the package @angular/router. Routing provides a complete routing library
with the possibility of multiple router outlets, different path strategies.
The angular Router is the main part of Angular platform. It allows developers to build single-page
applications with multiple views and allow navigation between views.

Angular supports SPA using routing module ngRoute. The routing module acts based on the URL.
It works as a browser navigation’s bar, and it was navigating between the pages.

 Enter URL in the address bar, and then the browser will navigate to the corresponding
page.

53
 Click on the link to the page and the browser will navigate to the new page.

 Click on the browser on the back or forward, and the browser will navigate backward or
forward according to the history pages.

Working of Router:

Whenever a user acts, such as clicking a link which loads a new page in the browser, the Router
intercepts the browser behavior, and show and hide the view hierarchy.

If the Router finds the current application, it requires particular functionality, and it can be lazy
to load the module on demand.

We can navigate to new views when the user clicks a button or select from a dropbox or in
response to some other stimulus from any source. The router logs in the browser history so back
and forward button works well.

To define navigation rules, we associate navigation path with our component. A path uses a URL-
like a syntax that integrates our program data in the same way that template syntax integrates.
We can apply program logic to choose views to show or hide, in response to user input and our
access rules.

How to Set-up routing in Angular 8?

Routing could be easily added to a project. We were prompt if we have the message, “ Would
you like to add angular routing?”(Y/N),if we answered by Y. The angular Router was set up in
our project without having added it manually.
Otherwise, if we have no option like that, then we have to import it manually in our project.

 Firstly open our project where we have to import or add the routing module.

 After that, for creating the module we have to write the command ng g c home –
spec=false.

54
 In the same directory, we have to write the command ng g module app-routing
According to the following screenshot.

55
Angular brings many improved modules to the Angular ecosystem, including a new router called
the component router. The component router is highly configurable and features packed Router.
Features included are standard view routing, nested child routes, named routes, and route
parameters. The concept related to the Router are:

The Router-outlet

The Router-outlet is a directive accessible from the router library where the Router inserts the
component and gets matched based on the current browser’s URL. We can add multiple outlets
in our angular application, which enables us to implement advanced routing scenarios.

<router-outlet></router-outlet>

Routes And Paths


Routes are definitions comprised of a path and component attributes. The path mention to the
part of the URL that determines a unique view that can be displayed, and refer to the Angular
component that needs to be associated with a path.

In a component, each route maps a URL path.

56
The path could take a wildcard string (**). The Router selects this route if the called URL doesn’t match
the explained routes. It can be used for displaying a “Not Found” view or redirecting to a specific view if
there is no match.

{path:’contacts’, component: ContactListComponent}

If the route definition is provided to the router configuration, the router will
render ContactListComponent when the browser URL for the web application /contacts.

Route Params
To creating the routes with parameters is a common feature in web apps. The angular Router
allows us to access parameters in different ways. We can create a router parameter using the
colon syntax.

{path:‘contacts/:id’, component: contactDetailcomponent}

Route Guard
A route guard is the feature of the Angular Router which allows the developer to run logic if a
router is requested, and it is based on the logic. It allows and denies the user access to the route.
We can add a route guard by implementing the CanActivate interface available
from @angular/router package. It can activate() method which holds the logic to allow and deny
access to the route.
Class MyGuard implements CanActivate {

can activate () {

return true;

57
Navigation Directive
The Angular Router provides the router link directive to create the navigation links. This directive
generates the path associated with the component to navigate.

For example:
<a[routerLink]= " ‘/contacts' ">Contacts</a>.

Angular 8 Directives
Directives are instructions in the DOM (Document Object Model). It specifies how to place our
business logic in Angular. The directive is markers on a DOM element that tell Angular to attach
a specified behavior to that DOM element or even transform the DOM element and its children.
Mostly directives in Angular starts with ng- where ng stands for Angular, and it extends the
HTML.

There are three kinds of directives:

Component Directives

Components are the most common of the directives. It contains the details of how the
component should be processed, instantiated, and used at runtime. The component comprises
meta-data.

58
Structural Directives
Structural Directives are done in the elements section. These directives are used to manipulate
and change the structure of the DOM elements. Structural directives have a star (*) sign before
the directive. Like as,* ngIf, *ngFor, and *ngSwitch directive.
 *ngIf Directive: The *ngIf allows us to Add/Remove DOM Element.
 *ngSwitch Directive: The *ngSwitch will enable us to Add/Remove DOM element. It is
same as the switch statement of C#.
 *ngFor Directive: The *ngFor directive is used to repeat a part of HTML template once
per each item from an iterable list (Collection).
Attributes Directives: It change the look and behaviorof the DOM.
. For example: ngClass, ngStyle etc.
 NgClass Directive: The ngClass Directive is used to add or remove CSS classes to an
element.
 NgStyle Directive: The ngStyle Directive facilitates you to modify the style of an HTML
element using the expression. We can also use the ngStyle Directive to change the style
of our HTML element dynamically.

Structural Directive Attribute Directive

Structural directives are applied to The component has their view (HTML and styles)
<template> elements and used to add or because of that, there can be one component on a
remove content (stamp and template). host element, but multiple directives.

How to Create Custom Directives?

We can create our custom directives to use in Angular components with the help of the command line.
The command which is used to develop the Directive using the command line is as follows-

59
ng g directive name of the Directive

e.g

ng g directive change text

It is seen in the command line as given in the below code-

C:\projectA7\angular7-app>ng g directive change text

CREATE src/app/change-text.directive.spec.ts (241 bytes)

CREATE src /app/change-text.directive.ts (149 bytes)

UPDATE src/app/app.module.ts (565 bytes)

The above files, i.e., change-text directive.spec.ts and change-text.directive.ts created and
the app.module.ts is updated.
app.module.ts
The ChangeTextDirective class has been included in the declarations in the above file. The class
is also imported from the file given below-

Angular 8 Pipes
Pipes are a useful feature in Angular. These are the simple way to transform values in an Angular
template. It takes the integers, strings, array, and dates as input separated with | to be converted
in the format as required and display same as an in the browser.
Inside the interpolation expression, we define the pipe and use it based on the situation because
there are many types of pipes. We can use in our angular applications. A pipe holds in data as
input and transforming it into the desired output. Some values benefit for a bit of editing. We
may notice that we want many of the same transformations repeatedly, both within and across
many applications.

We can almost think of them as styles, and In fact, we might like to apply them in our HTML
templates.

60
Syntax:
{{title | uppercase}}

See an example of the pipe; previously, we display the title text in upper and lower case with the
help of pipes.

Example:
Define a variable named “title” in the component.ts file.

Import {Component} from ‘@angular/core’;

@Component ({

selector: ‘app-root’,

templateUrl: ‘.app.component.html’,

styleUrls: [‘./app.component.css’]

}]

title=’my-first-app’;

Here, we are using the pipe symbol in component.html file

<h1>

{{ title | uppercase}} <br>

</h1>

<h1>

{{ title | lowercase }} <br>

</h1>

61
Run ng serve and see the result. You will see the following result. We can see that pipes have
changed the title in upper and lowercase.

Built-in Angular pipes

Angular has a stock of pipes such as Date Pipe, Uppercase Pipe, Lowercase Pipe, currency pipe,
and percent pipe. They are available for use in any angular template. Angular doesn’t have the
Filter Pipe or any Orderbypipe. Angular doesn’t provide the pipes for filtering and sorting the
lists. Pipes are an excellent way to encapsulate and share a collective display-value
transformation.

 AsyncPipe

 Currencypipe

 Datapipe

 Decimalpipe

 Jsonpipe

 Percentpipe

 Lower case pipe

 Upper case pipe

 Slicepipe

 Title case pipe

62
Parameterizing a pipe in Angular 8

We can also move a parameter to the pipe; we can use the HTML code to pass the parameter.

app.component.html
<h1>

Rohan’s birthday is {{ birthday | date:”dd/mm/yyyy”}}

</h1>

Chaining pipes
We can chain pipes together and creates useful combinations and also can use the lowercase and
upper case pipe in our example.

app.component.html

<h1>

Rohan’s birthday is {{birthday | date | uppercase}}

</h1>

Pure and Impure pipes

There are two categories of pipes:

1. Pure

2. Impure

By default, pipes of angular are pure. Every pipe we have seen are pure and built-in pipes. We
can make the pipe impure by setting the pure flag into false.

63
Pure pipes
Angular executes the pure pipe only when if it detects the perfect change in the input value. The
real difference is either in the shift to the primitive input value (Number, Boolean, Symbol, String)
or a changed object reference (Array, Function, Object, Date).

Impure pipes
Angular executes the corrupted pipe during every component change detection cycle. The
impure pipe is called often every keystroke or mouse-move.

How to Create a Custom Angular Pipe?

To create a custom pipe, we create a new ts file and use the code according to work, and we have
to import Pipe, Pipe Transform from Angular/Core.

Create a sqrt custom pipe.

component.ts file

import {Pipe, PipeTransform} from

‘@angular/core’;

@Pipe ({

name: ‘sqrt’

})

Export class SqrtPipe implements PipeTransform {

transform (val: number) : number{

Return Math.sqrt(val);

64
We have to make changes in the app.module.ts. Create a class named as SqrtPipe.

This class will implement PipeTransform. The transform method defined in the class can take
arguments as the number and will return the number after taking the square root.

We have to add the same code in app.module.ts file


module.ts file:

import { BrowserModule } from '@angular/platform-browser';

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

import { AppComponent } from './app.component';

import { NewCmpComponent } from './new-cmp/new-cmp.component';

import { ChangeTextDirective } from './change-text.directive';

import { SqrtPipe } from './app.sqrt';

@NgModule({

declarations: [

SqrtPipe,

AppComponent,

NewCmpComponent,

ChangeTextDirective

],

imports: [

BrowserModule

],

providers: [],

65
AppComponent]

})

export class AppModule {

Now, use sqrt pipe in the component.html file.

component.html file: <h1>Example of Custom Pipe</h1>

<h2>Square root of 225 is: {{225 | sqrt}} </h2><br>

<h2>Square root of 164 is: {{164 | sqrt}} </h2><br>

Output:

What is Binding?

Binding is the process which generates the connection between the application UI and the data
which comes from the business logic. In Angular, it is called the automatic synchronization of the
data and the view.

Data Binding in Angular 8

Data binding is the most important and essential features in any software development language.
It is a powerful feature of Angular. Angular Data binding is used for communication. It allows us
to define the connection between the component and view. So, we can say that data binding is
passed from component to view. It makes it easy to identify interactive applications without

66
worrying about pushing and pulling the data. It is mainly used to communicate between our
Typescript code and another component.

It has mainly two parts:


HTML Template

It contains view for the component (HTML elements: input, select, button, etc.)

Component Class

It contains logic for a component like classes, variables, functions, API calls, etc. The interaction
between the HTML template and component class can be done through data binding. In simple
words, “Data Binding is communication between typescript code of our component and our
template which user sees.” Data binding can be one-way data binding or two-way data binding.

One way data-binding:

It is a simple one-way communication where HTML template is changed when we make changes
in typescript code. The value of the model is used in the view (HTML page), but we can’t update
the model from the view in one-way data binding. Property binding, Event binding, and String
interpolation are an example of one-way data binding.

Two-way data binding

In two-way data binding, automatic synchronization of data happens between the model and the
view. Here, changes are reflected in both components. When we make changes in the model
from the view, and when we make changes in view, it will be reflected in the model.

67
This will happens immediately and automatically, ensures that the HTML template and the
Typescript code are updated at all times.

Types of Data Binding:

 String Interpolation

 Property binding

 Event Binding

 Two Way Data Binding

68
String Interpolation

String Interpolation is a one-way data-binding technique which is used to output the data from
a TypeScript code to HTML template (view). It uses the template impression in double curly
braces to show the data from the component to the view. {{data}}
String interpolation sums the value of a property from the component.

Syntax : li>Name: {{user.name}}</li>

<li>Email: {{user. Email}}</li>

Property Binding

Property binding is a technique, which will help to bind values to the properties of HTML elememts. It is
also a one-way data binding approach. In property binding, we bind a characteristic of a DOM element in
a field which defined property in our component Typescript code. Property binding helps us to bind the
values to the target property of the element property surrounded within the square brackets.

<img [src]="”imgUrl”/">

<input type="”email”[value]=”user.email”">

Event binding

Event binding is used to hold the events lifted from the DOM such as button click, mouse move,
etc. in Angular 8. When the DOM event happens (e.g., Click, change, key up), it calls the specified
method in the component. In the following example, the cookbacon() method in the component
is called when the button is clicked:

For example:

<</code>button (click)=”cookBacon()”></button>

69
Two-way Data Binding

In one-way data binding, any changing in the template (view) was not considered in the
component Typescript code. To solve this problem, Angular produces two-way data binding.

The two-way binding has a vital feature to update data from component to view and view to the
element.

In two way data binding, property binding and event binding are combined. For two-way data
binding, we have to enable the ngModel directive.

Syntax: [(ngModel)]=”[property of our component]”

Angular 8 Forms
Angular forms are used to handle the user’s input. We use Angular form in our application to
authorize users to log in, to update profile, to enter information, and to perform many other
data-entry tasks.

In Angular 8, there are two approaches to handle the user’s input through forms:

 Reactive forms

 Template-driven forms

Both methods are used to collect user input event from the view, validate the user input, create
a form model to update, and provide a way to track changes.

70
Reactive and template-driven forms process and manage form data differently. Each offers
different advantages.

Reactive forms
Reactive forms are more robust, and they are more scalable, reusable, and testable. If forms are
a vital part of our application or are already using reactive patterns for building our app, handle
responsive forms.

Template-driven forms
It is useful for adding a simple form to an app, such as an email list signup form to an app, such
as an email list signup form. It is easy to add to an app, but they don’t scale as well as reactive
forms. If we have fundamental form requirements and logic that can be managed in the template
and use template-driven forms.

Difference between Reactive and Template-driven Forms:

Index Reactive Forms Template-driven Forms

Responsive forms are more explicit.


Setup (form Template-driven forms are less
They are created in the component
model) explicit. Directives create them.
class.

Data model Structured Unstructured

Predictability Synchronous Asynchronous

Form Validation Functions Directives

Mutability Immutable Mutable

71
Similarities between Reactive and Template-driven Forms
There are some building blocks which are allocated by both reactive and template-driven forms:

 FormControl: It is mainly used to track the value and authentication status of an


individual form control.
 FormGroup: It has been used to track the same values and level of a collection for the
form control.
 FormArray: It isused to route the same values and status for the array to form controls.
 ControlValueAccessor: It is used to create a gap between Angular native DOM elements
and.Form Control instances

Form Model Setup


Form model setup is used to trace value change between Angular forms and form input elements.
Take an example to see the form model is defined and created.

Form model setup in Reactive forms:


See the component with an input field for a single control implemented using reactive forms

The form model is the source of truthfulness in reactive forms. The source of truth supply the
value and status of the form element at a given point of time.

Here, in the above example, the form model is the form Control instance.

72
In reactive forms, the form model is clearly defined in the component class. After the reactive
form directive links the existing FromControl instance to a specific form element in the view using
a value accessor.

Form Model setup in Template-driven Forms


See the same component with an input field for a single control implemented using template-
driven forms.

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

@Component({

selector: 'app-template-favorite-color',

template: `

Favorite Color: <input type="text" [(ngModel)]="favoriteColor"> `

})

export class FavoriteColorComponent {

favoriteColor = ''

73
}

In template-driven forms, the source of the truth is template itself.

The form model abstraction promotes simplicity over the structure. The template-driven form
directive NgModel creates and organizes the FormControl instance for any form element. It’s less
explicit, but it eliminates the direct control over the form model.

Angular 8 Module
It is services, directives, controllers, filters, and configuration information. angular.module is
used to configure the $injector. The module is a container of the different parts of an application.
Controllers always belong to a module. In case of developing a website, the header, footer, left,
center, and the right section become part of a module.

In Angular, a module is a technique to group the components, directives, pipes, and services
which are related, in such a way that is combined with other modules to create an application.

74
Another way to understand Angular modules is classes. In class, we can define public or private
methods. The general purposes are the API that other parts of our code can use to interact with
it while the individual techniques are implemented details which are hidden.

In the same way, a module export or hide components, directives, pipes, and services. The
exported elements are used by other modules, while that are not export in the module and
cannot be accessed by other modules of our application.

Creating a Module

A module is created by using the Angular function angular.module

<div ng-app="”myApp”">…</div>

<script>

var app= angular.module(“myApp”,[]);

</script>

We have to use the decorator NgModule to define modules

import {NgModule} from ‘@angular/core’;

@NgModule({

Import:[…],

declarations:[…],

75
bootstrap:[…]

}]

export class AppModule{}

Use of Module

In the above example, we turned the class AppModule into an Angular module by using the
NgModule decorator. The NgModule decorator needs at least three properties:
 Imports
 declarations
 bootstrap
The property imports expect an array of modules. Where we define the piece of the puzzle.
The property declaration expects an array of components, directives, and pipes that are the part
of the module.

76
The bootstrap property is when we define the root component of the module. However, this
property is also an array, 99% of the time, and we are going to explain only one element.
 Note: There are particular circumstances where more than one component is required
to bootstrap a module, but we are not covering those edge cases.
Example:
app/app.component.ts file
import { Component }from ‘@angular/core';

@Component ({

selector:'app-root',

template:

'&lt;h1&gt;my angular app&lt;/h1&gt;'

})

app/app.module.ts file
import { Ngmodule } from ‘@angular/core’;

import {BrowserModule } from ‘@angular/platform-browser’;

import {AppComponent} from ‘./app.component’;

@NgModule({

77
imports:[BrowserModule],

declarations: [AppComponent],

bootstrap:[AppComponent]

})

export class AppModule {}

app.component.ts is a “hello world” component, nothing is interesting there. In the other hand,
the structure that we’ve seen before for defining a module but in the case, we are defining the
modules and components that we are about to using.
The first thing is that we notice our module is importing the BrowserModule like an explicit
dependency. The BrowserModule is a built-in module which exports basic pipes, directives, and
services. Apart from previous versions of Angular, we have to precisely import those
dependencies to use directives like *ngFor or *ngIf in our templates.
The root component of our module is the AppComponent where we have to list it into
the bootstrap array. Because in the declaration property we have supposed to define all
elements or pipes that make our application reactive, we have to set the AppComponent again.
Before moving on, there’s a necessary clarification to make.

There are two types of modules:


 Root modules
 Features modules
We have one root component and many possible secondary components in any application, and
only have one root module and zero or more feature modules. To understand bootstrap, we need
to know the root module.

Bootstrapping an application in Angular 8

Bootstrapping refers to the starting of a self-dependent process that is supposed to process


without external input. To bootstrap our module based application, we need to inform Angular,

78
which is our root module to perform the compilation in the browser. This compilation in the
browser is known as “Just in Time” (JIT) compilation process.
main.ts file
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

It is possible to perform the compilation like a build step to our workflow. This method is called
“Ahead of Time” (AOT) compilation and will require a slightly different bootstrap process.
NgModule metadata

NgModule is defined through a class decorated with the help of @NgModule(). The
@NgModule() decorator is a function which extracts a single metadata object, whose properties
describe the module. The most important features are given below.
 Declarations: The components, directives, and pipes belong to the NgModule.
 Exports: The subset of declarations should be visible and usable into the component
templates of other NgModules.
 Imports: Component templates need the other modules whose exported classes are
declared in the NgModule.
 Providers: Creators of services that NgModule contributes to the global collection of
services; they become accessible in all parts of the app. (we can also specify providers at
the component, which is selected).
 Bootstrap: The main application view, also called the root component, which hosts all the
app views. Only the root NgModulewill set the bootstrap property.
src /app/app.module.ts file

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

import { BrowserModule }from '@angular/platform-browser';

79
@NgModule ({

imports:[BrowserModule ],

providers:[Logger ],

declarations:[ AppComponent ],

exports:[ AppComponent ],

&nbsp;bootstrap:[ AppComponent ]

})

&nbsp;export class AppModule{ }

App Component is included in the exports list for illustration; it is not necessary in the example.
A root NgModule has no any reason to export anything from file because the other modules
does’nt import the root NgModule.
NgModules and Components

NgModules provide a compilation context for its components. A root NgModule has a root
component which is created during the bootstrap working, but NgModule can include only the
additional components. Which load through the router or created by the template.
A component and its template simultaneously define a view. A part contains a view hierarchy,
which allows us to represent the complex aimless area of the screen that can be created,
modified, and destroyed as a unit. A view hierarchy can define in components which belong to
different NgModules.

80
When we create a component, it is connected directly with a single view, called the host view.
The host view is the root of a view hierarchy, which contains embedded views, which are, in turn,
the host view of other components. Those components can in the same NgModule and be
imported from other NgModules. Views in the tree can nested to any depth.
 Note: The hierarchical structure of views is a key factor in the way Angular detects and
responds to change in the DOM and app data.
NgModules and JavaScript modules

The Ngmodule system is different from the JavaScript module system for managing collections
of JavaScript objects. These are complementary module systems that we can use together to
write our app.
In JavaScript, every file is a module and object defined in the file belong to that module. The
module. The module declares some objects by marking them with the export keyword. Other
JavaScript module use import statement to access public objects from other modules.

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

import { AppComponent } from './app.component';

export class AppModule { }

Difference between Module and Component

Module Component

A module is a collection of
A component in Angular is a building block of the application
components, services, pipes,
with an associated template view.
directives, and so on.

81
The angular apps will contain Each component can use another component, which is
many modules, each dedicated declared in the same module. To use components declared
to a single purpose. to other modules, they need to export from this module.

Denoted by @ngModule Denoted by @component

Angular 8 Observables
Observables provide support for passing messages between publisher and subscription in our
application. The observables can deliver the multiple values of any type like literal, messages,
depending on the content.
It is an object that defines the callback method to handle the three types of notification that an
observable can send. These are the following.

 Next: Required. The handler for each delivered value called zero or more type after
execution start.
 Error: Optional. The handler is used for error warning. An error stops the execution of the
observable instance.
 Complete: Optional.The execution for the execution complete notification. Delayed value
can continue delivering to the next handler after the execution complete.

An observable deliver multiple values of any type-literals, messages, or events, depending on the
context. The API for receiving values is the same whether the values are offered on the context.

82
Because setup and teardown logic are handled by the observables, And our application code only
needs to subscribing to consume values, and when it done, or unsubscribing.

Basic usage and terms

It is the function that is executed when a consumer calls the subscribe() method. To execute the
observable we have created and begun receiving notifications, we call the subscribe() method,
passing an observer. This is a JavaScript object which defines the handlers for the notifications
we receive. The subscribe () call returns a subscription object than the unsubscribe () method,
what we call to stop receiving notifications.

83
Chapter 3 MongoDB

MongoDB Introduction
MongoDB is a NoSQL category, open-source document-oriented database. It is popular due to its
scalability & flexibility feature needed for various querying and indexing of high volume of data
storage.

Basic requirements for Learning MongoDB

 Learn concepts of any programming language

 In-depth knowledge of JavaScript

 JSON knowledge will undoubtedly be a great help

 Basic idea of RDBMS

 Idea of any text editor

MongoDB Architecture

From the traditional architecture of RDBMS, MongoDB offers the features of scalability,
performance, flexibility, Global deployments. It mainly consists of:

 Database: The MongoDB server stores many databases with their collection of files on
the file system. We can define it as an actual space for the collection of data.
 Collection: A collection behaves like a table in RDBMS. It contains a group of documents.
A collection does not follow any specific structure.
 Document: Basically, in MongoDB collection of the record is called the document, which
has field name & values. These are associated with a dynamic schema. With this dynamic
schema feature, it accepts various data types in common fields. So, we are not forced to
have same data types in common fields.

84
 -Id: This field represents a unique value in the document of MongoDB. It is a must
required field. If a document is created without this field, the MongoDB automatically
creates it. It acts as a primary key for the document.
 Cursor: Results of any type of query can be retrieved with the help of a pointer to the set
of results called cursor.
 Field: The pair of name and value in a document is the field. These are just like the
columns of relational databases.
 JSON: It is the JavaScript object notation. It is an accessible format to express structured
data in a human-readable format.

MongoDB NoSQL: As MongoDB is a NoSQL database, we need to know about what exactly is
NoSQL. The notation NoSQL means “not only SQL.” The term was coined by Carlo Strozzi in 1998.
It means NoSQL can apply the query concepts of SQL. NoSQL is a non-relational database that is
quite easy to scale. Companies like Facebook, Twitter, and Google that collect a huge amount of
user data every day, need NoSQL.

Why do we need NoSQL?

As RDBMS is used for a significant volume of data, the response time of the system becomes
quite slow. This problem can be resolved by scaling up our systems. “Scale up,” or the vertical
scaling is done by upgrading the hardware, but it’s costly for the organization.
Another approach is to distribute the excess database load on multiple numbers of the host. This
approach is called “scaling out.”
Since NoSQL is a non-relational database here, the scaling out is much better.

Features of NoSQL

1. It is a Non-relational database.

2. It does not need a schema.

85
3. It follows a distributed approach.

4. It has a straightforward API.

MongoDB vs RDBMS: MongoDB being the schema-less database, supports the object model.
Here any field can be indexed. It can run on multiple servers.
RDBMS stands for the relational database management system. It provides a high level of
security for information. It is quite quick and provides primary keys for the fast execution.
Difference between MongoDB and RDBMS

RDBMS MongoDB

It is a non –relational and NoSQL document-


It is the relational database
based database.

Other than usual rows and columns, it utilizes the


It needs tables with relations to store data.
document storage format i.e., BSON.

A proper designing of the table, data


Coding does not need a table, and objects can be
structure, and relations need to be done
very easily modified at a lesser cost.
before coding.

Here SQL language is used for coding. JSON can be used other than SQL.

Javascript client is provided here for various


Javascript client is not supported
queries.

The primary key is used to distinguish the


The MongoDB database provides the default id.
rows exceptionally.

86
Join is not used, but it supports embedding
Transactions, including multiple tables, are
documents inside another one keeping the size
done by Joins.
limit up to 16mb.

The execution process is slow as compared


It is almost 100 times faster than RDBMS.
to NoSQL.

MongoDB Installation
Operating Systems for MongoDB Installation

You can run MongoDB on the following Operating Systems:

 Linux
 Debian
 RHEL / CentOS 6, 7 and 8
 macOS
 Ubuntu
 Windows Server
MongoDB on Linux: To run MongoDB, you can use Linux version 2.6.36 or later, with XFS or EXT4
file system. The performance of XFS is much better with MongoDB.
MongoDB on Debian: MongoDB 4.2 support Debian 10 “Buster” & Debian 9 “Stretch”. It only
provides the package for 64-bit builds of this release.
MongoDB with macOS: MongoDB 4.2 or updated released support macOS version 10 on Intel
x86-64.
MongoDB on Ubuntu: MongoDB is already added to the Ubuntu package. It uses Ubuntu version
16.04.

87
MongoDB on Windows: MongoDB can be installed in both 32-bit and 64-bit format by the
installers. The difference between the two installers is that 32-bit is appropriate for test
environment and 64-bit for the production environment.
MongoDB installation on Windows

First of all, you have to download the latest version of MongoDB.

Steps for downloading MongoDB in Windows:


 Open your favorite browser and go to the below link to download MongoDB:

https://www.mongodb.com/download-center/community

Various variants of downloading are available like Solaris, Mac ios, Windows, Linux. Here, select
the latest version or the version that your system supports. Windows version can be known by
the execution of the following command:

C:\ wmic os get osarchitecture


 After choosing the version and operating system, click on the download button. Once
downloaded, save it as MSI file wherever you want.

88
 When the downloading is complete open the MSI file. In the start up screen click on the
Next button.

 Accept the terms and conditions and click on next.

 To install all the components, click on the Complete button, but if you want some selective
components then select custom option.

89
 Click next after selecting “Run service as network service user”. Note the data directory
as it will be needed afterward.

 Hit the Install button to let the installation begin.

 Click on the Next button once the installation is completed.

90
 Finally, click on the Finish button to let the installation complete.

Steps for Setting up MongoDB environment

 MongoDB is installed in the following path:

C://programfiles/mongodb/server/version/bin

91
Inside the bin, we can see several files where the main two files are mongo.exe and mongod.exe.
mongo.exe is the command-line shell to work with the database, and mongod.exe runs in the
background.

 First time when we execute

C:\mongodb\bin\mongod.exe

You find an error message that c:\data\db not found as MongoDB demands data folder to store
the databases. Create a new folder named as data in the C drive of your computer by using
explorer. Create another folder called db inside this data folder.

The default path will be: C:\data\db

 Now execute mongod.exe again on command prompt and allow access, we see that it is
ready and waiting for the connection.

 Now we open one more terminal to execute mongo.exe.

C:\mongodb\bin\mongo.exe

MongoDB Data Types

MongoDB Data Types: In MongoDB, data is stored in BSON format, which is the binary encoded
form of JSON. By using BSON format, remote procedure call (RPC) can be used in MongoDB. In
MongoDB, each data type has two things. First is the alias & second is the number which is used
to search any particular record within its database. Nearly all the data types used in JavaScript
can be used in MongoDB.
 Integer: Data type used to store a numerical value. Both 32 & 64-bit integers are
supported depending on the server.
 Boolean: This data type is used to store a Boolean i.e., either true or false values.
 Double: It is used for storing floating-point data.

92
 Min–Max keys: These keys are used for comparison of values against the lowest & the
highest BSON elements.
 Arrays: Arrays are stored by implementing an array of data types. Many other values can
also be stored under a common single key.
 Object: It is used for embedding documents.
 String: It is the most common data type used to store data that must be UTF-8 valid.
 Symbol: It is generally used for language having a specific type of symbol. It is identical to
the string.
 Null: It is used for storing a null value.
 Date: Just like the unique time format, here date is used to store the current date & time.

MongoDB Insert Documents


MongoDB Insert Documents: Insert operations create a collection if it does not exist currently.
There are three methods to insert documents into a MongoDB database.
 insert()
 insertOne()
 insertMany()
 Insert() method:
This method is used to insert one or more documents in the collection. Each document is given
as a parameter to the method.

Inserting a single document:


Syntax:
db.collectionName.insert({name: "value"})

Since MongoDB uses JSON format documents, so the document has{name,”value”}.

Example
db.books.insert({authorname:"Chitra Divakaruni"})

The above example inserts a document with content {authorname:”Chitra Divakaruni”}

93
To see the documents of the collection, use the command:

db.collection.find()

If you do not specify any –id, the MongoDB creates it automatically.

Example: use booksdb


switched to db booksdb

db.books.insert({authorname: "Chitra Divakaruni"})

WriteResult({ "nInserted" : 1 })

db.books.find()

{ "_id" : ObjectId("5ded3592e96690a9c945a59d"), "authorname" : "Chitra Divakarun i" }

Parameters of insert()

Parameter Type Description

It can be either a document or an array of documents to be


document Document/array
inserted into the collection.

Acknowledgment is needed for write operations to a replica


set, shards, or standalone mongodb. This optional parameter
writeconcern Document
is a document describing the level of acknowledgment of
write concern.

This is an optional parameter. If its value is set to true, the


documents are inserted into a sorted array, and if any of the
ordered Boolean
documents contain an error, the remaining documents in the
array will also not be processed. If the set value is false, then

94
an unordered insert operation is performed. Even if an error
occurs in a document, remaining documents are processed
without fail.

Inserting multiple documents

Multiple documents are inserted in the form of an array. Here, documents are enclosed within []
and are separated by commas. The array name is passed to the insert method as:

Syntax:
db.collectionName.insert(arrayName);

This way of inserting multiple documents is called Bulk insert.

> var employee=

... [

... {

... Department: "MCA",

... details: { Name: "Akkash Deep", Designation: "Assistant Professor"},

... Profile: {Experience: 15, Area: "Network"},

... Type:"Regular Faculty"

... },

... {

... Department: "IT",

... details: {Name: "Anita", Desigination: "Associate Professor"},

95
... Profile: {Experience: 25, Area: "Testing"},

... Type:" Regular Faculty"

... }

... ];

> db.institute.insert (employee);

BulkWriteResult({

"writeErrors" : [ ],

"writeConcernErrors" : [ ],

"nInserted" : 2,

"nUpserted" : 0,

"nMatched" : 0,

"nModified" : 0,

"nRemoved" : 0,

"upserted" : [ ]

})

Inserting multiple documents with Bulk

MongoDB(latest version) provides an API that can perform the multiple write operations
together in bulk.

1. First of all, you have to initialize a bulk operation builder for a specific collection. The list
of operations to be performed is maintained by an unorder operations builder returned
by the bulk operation.

2. Now add insert operations to the bulk object.

96
3. Finally, execute the bulk operation by calling the execute method on the bulk object.

1. insertOne() method:
To insert a single document into the collection, insertOne() method is also used. The specified
collection gets created if it does not exist in the database.

The output is quite different from the insert() method.

use booksdb

switched to db booksdb

var author=db.books.insertOne({“authorname”: "Chetan Bhagat"})

author

"acknowledged" : true,

"insertedId" : ObjectId("5aed3592e96690a9c945a60de")

}
insertMany() method:

97
You can also use insertMany() method for inserting multiple documents like insert(). It helps in
inserting an array of documents. Here also, the output is quite different from insert().

var books1 = db.books.insertMany([“Novel”: 20}, {'Magazine': 10}])

books1

"acknowledged" : true,

"insertedIds" : [

ObjectId("671a22a911b82a1d94c01347"),

ObjectId("671a22a911b82a1d94c01348")

Aggregate Function
syntax : db.collectionName.aggregate(pipeline options)

In
In SQL Description
MongoDB
Passes the fields to next stage with existing Fields or with New fields.We can add new
Select $project
Fields dynamically
This will filter the documents and will pass only matching documents to next pipeline
Where $match
stage.
limit the first x unmodified documents and pass them to next stage of pipeline. x is
Limit $limit
the number of the documents which will pass through the next stage of pipeline.
This will group the documents and pass them to the next stage of Aggregation
GroupBy $group
pipeline.
OrderBy $sort It will change the order of documents either in ascending or descending.
Sum $sum To calculate the sum of all the numeric values.
Join $lookup It will perform the left outer join with another collection in same database.

98
Collection

A collection is the equivalent of an RDBMS table. A collection exists within a single


database. Collections do not enforce a schema. Documents within a collection can have different fields.

Create a Collection
The following command can be used to create a collection. The details on this command can be
found on this page.

db.createCollection("collectionName");

Insert a Document in a Collection


Once a collection is created, the next step is to insert one or more documents. Following is a
sample command for inserting a document in a collection.

//
// Insert single document
//
db.<collectionName>.insert({field1: "value", field2: "value"})
//
// Insert multiple documents
//
db.<collectionName>.insert([{field1: "value1"}, {field1: "value2"}])
db.<collectionName>.insertMany([{field1: "value1"}, {field1: "value2"}])

Save or Update Document


The save command can be used to either update an existing document or insert a new one
depending on the document parameter passed to it. If the _id passed matches an existing
document, the document is updated. Otherwise, a new document is created. Internally,
thesave method uses either the insert or the update command.

db.<collectionName>.save({"_id": new ObjectId("jhgsdjhgdsf"), field1: "value", field2: "value"});

Display Collection Records


The following commands can be used to retrieve collection records:

//
// Retrieve all records
//
db.<collectionName>.find();
//
// Retrieve limited number of records; Following command will print 10 results;

99
//
db.<collectionName>.find().limit(10);
//
// Retrieve records by id
//
db.<collectionName>.find({"_id": ObjectId("someid")});
//
// Retrieve values of specific collection attributes by passing an object having
// attribute names assigned to 1 or 0 based on whether that attribute value needs
// to be included in the output or not, respectively.
//
db.<collectionName>.find({"_id": ObjectId("someid")}, {field1: 1, field2: 1});
db.<collectionName>.find({"_id": ObjectId("someid")}, {field1: 0}); // Exclude field1
//
// Collection count
//
db.<collectionName>.count();

MongoDB Document

MongoDB Document is an entity in which zero or more ordered field-value pairs are stored.

In comparison to Relational Databases, it is analogous to a record or row in table.

Document in MongoDB follows BSON Specifications. BSON is binary encoded serialization of


JSON-like documents. With BSON, MongoDB Documents can be traversed easily. As BSON uses C
data types, encoding data to BSON or decoding from BSON is easier in most of the programming
languages. A document can have documents nested in them. MongoDB Documents are the
building blocks of a MongoDB Collection.

Structure of MongoDB Document

{
field1:value1;
field2:value2;
fieldN:valueN;
}
Document can contain N number of field-value pairs.

100
Node.js Connect to MongoDB
Following is an Example Node.js program to make a Node.js MongoDB Connection.

node-js-mongodb-connection.js
// URL at which MongoDB service is running
var url = "mongodb://localhost:27017";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

// Make a connection to MongoDB Service


MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Connected to MongoDB!");
db.close();
});

101
Chapter 4 Express.js

Express.js, or simply Express, is a web application framework for Node.js, released as free and
open-source software under the MIT License. It is designed for building web applications and
APIs. It has been called the de facto standard server framework for Node.js.

Install Express.js using NPM


To install express.js using npm, run the following command.

npm install express

To install it globally, run the above command with -g option. g for global.

npm install -g express

Once express.js is installed, you can import express.js into your node project using require
statement.

var express = require('express')

Now, express variable holds the reference to the express.js package.


If you do not install express.js prior to using it in your Node.js project, you will get an error as
below:

Express.js Routes

An Express.js Route defines how our Express application can respond to a client request to with
a specific URI (or path) and a specific HTTP request method (GET, POST, etc.).
To understand the need of an Express.js Route, let us dive into an example.
Create a basic Express application as shown below.
app.js

102
var express = require('express')

var app = express()

// start the server

var server = app.listen(8000, function(){

console.log('Listening on port 8000...')

})

All we have done is, instantiate an express application, started it at port 8000. Now, open a
browser and hit the url http://localhost:8000/.

The reponse is that it cannot GET the resource ‘/’.


Even there is no error in the console. The app is running fine.

Why is that? Because, in our Express application, we started the server, but did not define what
has to happen when a request hits the server.
This is where Express.js Routes come into picture. Following is a simple express route.

app.get('/', function (req, res) {

res.send('This is a basic Example for Express.js by Ekarma')

})

103
What does this route define? This route defines that, execute the statements inside the function,
when you receive a GET request with request url as /.

Let us define some routes in our app.js and start the server.
app.js
var express = require('express')

var app = express()

// route that gets executed for GET request and the request url path '/' or root

app.get('/', function (req, res) {

res.send('Home.')

})

// route that gets executed for GET request and the request url path '/hello/'

app.get('/hello/', function (req, res) {

res.send('Hello page.')

})

// route that gets executed for GET request and the request url path '/bye/'

app.get('/bye/', function (req, res) {

res.send('Bye page.')

})

// start the server

var server = app.listen(8000, function(){

console.log('Listening on port 8000...')

104
})

Start the express application..

Now hit the urls in the browser. By default, browser sends a GET request.
GET request with URL path http://localhost:8000/

GET request with URL path http://localhost:8000/hello/

GET request with URL path http://localhost:8000/bye/

Express route with multiple functions


You can provide one or more functions in the route. Each function is called a middleware.

105
app.js
var express = require('express')

var app = express()

// express route with multiple functions

app.get('/hello/', function (req, res, next) {

res.write('Hello page. ')

next()

}, function(req, res, next){

res.write('Hello again. ')

res.end()

})

// start the server

var server = app.listen(8000, function(){

console.log('Listening on port 8000...')

})

And in the browser, output is

You can also define these functions separately for modularity as shown below.
var express = require('express')

var app = express()

function hello(req, res, next) {

res.write('Hello page. ')

106
next()

function helloagain(req, res, next){

res.write('Hello again. ')

res.end()

// express route with multiple functions

app.get('/hello/', hello, helloagain)

// start the server

var server = app.listen(8000, function(){

console.log('Listening on port 8000...')

})

Express.js Middleware

What is Middleware?
Middleware is a function that can access request and response objects and can also
use next function in the application’s request-response cycle.
In this tutorial, we will learn how to define a middleware function in Node.js Express application
and how to make a call to the middleware function.
request – is the HTTP request that reaches the Express application when a client makes HTTP
request like PUT, GET, etc. It contains properties like query string, url parameters, headers, etc.
response – object represents the HTTP response that an Express application sends when it gets
an HTTP request.
next – next is used to continue with the next middleware in the middleware stack.
request-response cycle – The cycle of operations that get executed starting with a request hitting
the Express application till a response leaves the application for the request.
middleware stack – stack of middleware functions that get executed for a request-response
cycle.

107
The syntax is same as that of a JavaScript Function. It accepts request, response objects and next
function as arguments.

function logger(req, res, next) {

here, logger is the function name, req is the HTTP request object, res is the Node Response
Object and next is the next function in request-response cycle.
You can access all the properties and methods of request object req.
Similarly, you can access all the properties and methods of response object res.
Calling next() function inside the middleware function is optional. If you use next() statement,
the execution continues with the next middleware function in request-response cycle. If you do
not call next() function, the execution for the given request stops here.

Built-in middleware:

Starting with version 4.x, there is only one built-in middleware is express.static.

app.use(express.static(path.join(__dirname, 'public')));

This middleware function is based on serve-static, and is responsible for loading static assets
such as HTML files, images, and so on.

Third-party middleware:

There are a number of third party middleware, such as body-parser.mongoose, morgan and so
on. These can be installed by using command:

var bodyParser = require('body-parser');

app.use(bodyParser.json());

108
app.use(bodyParser.urlencoded({ extended: false }));

How to create a Middleware?

To create a middleware that will print the current time and save a book to database and render
a message.

First create the method for logging current time


//create a method to

var requestTime = function (req, res, next) {

req.requestTime = Date.now();

console.log("Current Time for Request"+req.requestTime );

next()

};

Express.js Router

Express.js Router is kind of nesting a mini server inside a server.


Create an Express.js Router
In the following example, we will create an API using router. The API is created separately to
demonstrate modularity.
router1.js
var express = require('express')

var router1 = express.Router()

// middleware that is specific to this router

router1.use(function timeLog (req, res, next) {

console.log('Requested URI Path : ', req.url)

109
next()

})

// define the home page route

router1.get('/', function (req, res) {

res.send('Birds home page')

})

// define the about route

router1.get('/about', function (req, res) {

res.send('About birds')

})

module.exports = router1

We created a router using express.Router() and then created some routing paths
app.js
var express = require('express')

var app = express()

var router1 = require('./router1')

app.use('/api/', router1)

// start the server

var server = app.listen(8000, function(){

console.log('Listening on port 8000...')

})

When we used app.use('/api/', router1) all the requests to the server with the URI path /api/ are
now routed to router1. And when you hit the URI http://localhost:8000/api/, ‘/’ routing in the
router 1 is executed. This is because, for router1, http://localhost:8000/api/ is considered as
base path.

110
Chapter 5 Node.js

Node.js is an open-source server side runtime environment built on Chrome's V8 JavaScript


engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime
environment for building highly scalable server-side applications using JavaScript.

Node.js tutorials will help you learn the essentials of Node.js starting from the basics to an
advanced level. These tutorials are broken down into sections, where each section contains a
number of related topics that are packed with easy to understand explanations, real-world
examples, useful tips, informative notes, and "points to remember" section.

These tutorials are designed for beginners and professionals who want to learn Node.js step by
step.

Basic knowledge of HTML, JavaScript and web application is recommended.

Setup Node.js Development Environment

In this section, you will learn about the tools required and steps to setup development
environment to develop a Node.js application.

Node.js development environment can be setup in Windows, Mac, Linux and Solaris. The
following tools/SDK are required for developing a Node.js application on any platform.

1. Node.js
2. Node Package Manager (NPM)
3. IDE (Integrated Development Environment) or TextEditor

NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0., so
there is no need to install it separately.

111
Install Node.js on Windows
Visit Node.js official web site https://nodejs.org. It will automatically detect OS and display
download link as per your Operating System. For example, it will display following download link
for 64 bit Windows OS.

Download Node.JS Installer for Windows


Download node MSI for windows by clicking on 8.11.3 LTS or 10.5.0 Current button. We have
used the latest version 10.5.0 for windows through out these tutorials.

After you download the MSI, double-click on it to start the installation as shown below.

112
Click Next to read and accept the License Agreement and then click Install. It will install Node.js
quickly on your computer. Finally, click finish to complete the installation.

Verify Installation
Once you install Node.js on your computer, you can verify it by opening the command prompt
and typing node -v. If Node.js is installed successfully then it will display the version of the Node.js
installed on your machine, as shown below.

Module in Node.js
Module is a simple or complex functionality organized in single or multiple JavaScript files which
can be reused throughout the Node. js application. Each module in Node. ... CommonJS is a
group of volunteers who define JavaScript standards for web server, desktop, and console
application.

Features of Node.js

Open-Source
Node.js is an open source framework MIT license that is supported by a huge community. Its
community is pretty much active have contributed to add new capabilities to Node.js
applications.

Simple&Fast
Since Node.js is built on Google Chrome’s V8 JavaScript Engine, its libraries are capable of fast
code execution.

113
Asynchronous
All the libraries of Node.js are asynchronous which means the Node.js based servers never
wait for an API to send back the response and move on to the next API.

High-Scalability
Because of the event mechanism, Node.js is highly scalable and aids the server in a non-
blocking response.

Single-Threaded
With the help of event looping, Node.js is able to follow the single-threaded model. This lets
a single program to handle multiple requests.

No-Buffering
One of the major functionalities of Node.js applications is that it never buffers any data.

Cross-Platform
Node.js can be easily built and deployed on various platforms like Windows, MAC, and Linux.

Let’s now advance further and see how to deploy the actual code on the browser. But before
that, you need to download and install in your systems. You can refer my other article to know
the complete dow

So now, let’s move further in this Node.js Tutorial, where I will talk about the most important
component of Node.js i.e., npm.

NPM (Node Package Manager)


NPM stands for Node Package Manager which as the name suggests is a package manager for
Node.js packages/modules. From Node version 0.6.0. onwards, npm has been added as default
in the node installation. It saves you from the hassle of installing npm explicitly.

NPM basically helps in two ways:

114
1. Provides and hosts Online repositories for node.js packages/modules which can be easily
downloaded and used in our projects. You can find them here: npmjs.com
2. Provides the Command line utility in order to install various Node.js packages, manage
Node.js versions and dependencies of the packages.

But now, you must be wondering what exactly these modules are and how do they help us in
building the Node.js applications. Well, in the next section of this Node.js tutorial, I will give you
a complete insight into Node.js modules.

Node.js Modules
The modules in Node.js represents various functionalities that are bundled up into single or
multiple JS files. These modules have a unique context, thus, they never interfere nor pollute the
scope of other modules.

These modules enable the code reusability and enhance the ease of usage. Node.js basically
provides three types of modules:

1. Core Modules
2. Local Modules
3. Third-Party Modules

Core Module

Since Node.js is a very lightweight framework, the core modules bundle the absolute minimum
functionalities. These modules generally get loaded when the Node process starts its execution.
All you need to do is, import these core modules in order to use them in your code.

Below I have listed down a few of the important Core modules.

Core Module Description

115
Contains classes, methods, and events required to create Node.js HTTP
http
server

url Contains methods for URL resolution and parsing in Node

querystring Contains methods to deal with a query string of Node

path Contains methods to deal with file paths

fs Contains classes, methods, and events to work with file I/O

util Contains utility functions that can be useful for programmers

You can load your core module, using the below code:

1. var module = require('module_name');

Lets now see, what are ‘local modules’.

Local Modules

The local modules of Node.js are custom modules that are created locally by user/developer in
the application. These modules can include various functionalities bundled into distinct files and
folders which can be easily distributed in the Node.js community using NPM.

These modules are loaded in a similar way to core modules. Let show you, how to do it using a
basic example.

Create your custom/local module.js file

var detail = {

name: function (name) {

console.log('Name: ' + name);

116
},

domain:function (domain) {

console.log('Domain: ' + domain);

};

module.exports = detail;

Include your module file in your main application file.

var myLogModule = require('./Local_module.js');

myLogModule.name('Edureka');

myLogModule.domain('Education');

Now you can execute these files using below command:

node application.js

Let me now show you what are external modules.

External Modules

You can use the external or 3rd party modules only by downloading them via NPM. These modules
are generally developed by other developers and are free to use. Few of the best external
modules are express, react, gulp, mongoose, mocha etc.

Globally Loading the 3rd party modules:

npm install --g <module_name>

Include your module file in your main application file:

117
npm install --save <module_name>

JSON File
The package.json file in Node.js is the heart of the entire application. It is basically the manifest
file that contains the metadata of the project. Thus, understanding and working with this file
becomes very important for a successful Node project development.

The package.json file generally consists of the metadata of the application, which is further
categorized into below two categories:

1. Identifying metadata properties: This consists of properties like the project name,
current module version, license, author of the project, project description etc.

2. Writing directly to file: You can directly write the necessary information into the
package.json file and include it, in your project.

By now you have already familiarized with the various components of Node JS application. In the
next section of this Node.js Tutorial, I will be sharing some Node Js basics so that we can start off
with the hands on.

Node.js Basics
Since Node.js is a JavaScript framework, it uses the JavaScript syntax. If you want to learn
JavaScript in detail, you can refer to this JavaScript Tutorial. For now, I will be brushing you up
with some Node.js basics like:

Data Types

Like any other programming language, Node.js has various datatypes, which are further
categorized into Primitive and Non-Primitive datatypes.

Primitive Data Types are:

1. String

118
2. Number
3. Boolean
4. Null
5. Undefined

Non-Primitive Data Types are:

1. Object
2. Date
3. Array

Variables

Variable are entities that hold values which may vary during the course of a program. To create
a variable in Node.js, you need to make use of a reserved keyword var. You do not have to assign
a data type, as the compiler will automatically pick it.

Syntax:

var varName = value;

Operators

Node.js supports the below operators:

Operator Type Operators

Arithmetic +, -, /, *, %, ++, —

Assignment =, +=, -=, *=, /=, %=

Conditional =?

119
Comparison ==, ===, !=, !==, >, >=, <, <=,

Logical &&, ||, !

Bitwise &, |, ^, ~, <<, >>, >>>

Functions

Functions in Node.js is a block of code that has a name and is written to achieve a particular task.
You need to use the keyword function to create it. A function is generally a two-step process.
First is defining the function and the second is invoking it. Below is the syntax of creating and
invoking a function:

Example: //Defining a function

function display_Name(firstName, lastName) {

alert("Hello " + firstName + " " + lastName);

//Invoking the function

display_Name("Park", "Jimin");

Objects

An object is a non-primitive data type that can hold multiple values in terms of properties and
methods. Node.js objects are standalone entities as there is no concept of class. You can create
an object in two ways:

1. Using Object literal


2. Using Object constructor

120
Example:

// object with properties and method

var employee = {

//properties

firstName: "Minho",

lastName: "Choi",

age: 35,

salary:50000,

//method

getFullName: function () {

return this.firstName + ' ' + this.lastName

};

File System
To access the physical file system, Node.js makes use of the fs module which basically takes care
of all asynchronous and synchronous file I/O operations. This module is imported using the below
command:

var fs = require('fs');

Some of the general use for the File System modules are:

 Read files
1. fs.readFile()

121
 Create files
1. appendFile()

var http = require('http');

var fs = require('fs');

http.createServer(function (req, res) {

fs.readFile('script.txt', function(err, data) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write(data);

res.end();

});}).listen(8080);

2. open()
3. writeFile()

 Update files
1. fs.appendFile()
2. fs.writeFile()
 Delete files
1. fs.unlink()
 Rename files
1. fs.rename()

So, with these commands, you can pretty much perform all the required operations on your files.
Let’s now move further with this Node.js Tutorial and see what are Events and how they are
handled in Node.js.

122
Events
As I have already mentioned, Node.js applications are single threaded and event-driven. Node.js
supports concurrency as it is event-driven, and thus makes use of concepts like events and
callbacks. The async function calls help Node.js in maintaining concurrency throughout the
application.

Basically, in a Node.js application, there is a main loop which waits and listens for events, and
once any event is completed, it immediately initiates a callback function.

Below diagram represents how the events are driven in Node.js.

One thing that you must note here is that, even though events look similar to callback functions
but the difference lies in their functionalities. When an asynchronous function returns its results
callbacks are invoked on the other hand event handling completely works on the observer
pattern. And in Node.js, methods which listen to the events are called the observers. The
moment, an event is triggered, its listener function automatically starts executing. Event modules
and EventEmitter class provide multiple in-built events which are used to bind events with event
listeners. Below I have written down the syntax for that.

Binding Event to an Event Listener

// Import events module

var my_Events = require('events');

// Create an eventEmitter object

var my_EveEmitter = new my_Events.EventEmitter();

Binding Event Handler to an Event

// Binding event and event handler

my_EveEmitter.on('eventName', eventHandler);

123
Firing an Event

// Fire an event

my_EveEmitter.emit('eventName');

Now let’s try to implement the things that I have discussed in this Node.js Event section. The
below code shows a simple representation of Event execution in Node.js.

var emitter = require('events').EventEmitter;

function iterateProcessor(num) {

var emt = new emitter();

setTimeout(function () {

for (var i = 1; i &lt;= num; i++) {

emt.emit('BeforeProcess', i);

console.log('Processing Iteration:' + i);

emt.emit('AfterProcess', i);

, 5000)

return emt;

var it = iterateProcessor(5);

it.on('BeforeProcess', function (info) {

console.log('Starting the process for ' + info);

124
});

it.on('AfterProcess', function (info) {

console.log ('Finishing processing for ' + info);

In the next section of this Node.js Tutorial, I will give you insights on one of the most important
module of Node.js called the HTTP Module.

HTTP Module
Generally, Node.js is used for developing server-based applications. But using the module, you
can easily create web servers that can respond to the client requests. Thus it is also referred to
Web Module and provides modules like HTTP and request that facilitate Node.js in processing
the server requests.

You can easily include this module in your Node.js application just by writing the below code:

var http = require('http');

Below I have written a code, that shows how a Web Server is developed in Node.js.

//calling http library

var http = require('http');

var url = require('url');

//creating server

var server = http.createServer(function (req, res) {

//setting content header

res.writeHead(200, ('Content-Type', 'text/html'));

var q = url.parse(req.url, true).query;

125
var txt = q.year + " " + q.month;

//send string to response

res.end(txt);

});

//assigning 8082 as server listening port

server.listen(8082);

126
Chapter 6 React.js

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets
you compose complex UIs from small and isolated pieces of code called “components”.

React is a JavaScript library used to build the user interface for web applications. React was
initially developed and maintained by the folks at Facebook, which was later used in their
products (WhatsApp & Instagram). Now it is an open source project with an active developer
community. Popular websites like Netflix, Airbnb, Yahoo!Mail, KhanAcademy, Dropbox and many
more use React to build their UI. Modern websites are built using MVC (model view controller)
architecture. React is the ‘V’ in the MVC which stands for view, whereas the architecture is
provided by Redux or Flux. React native is used to develop mobile apps, the Facebook mobile
app is built using React native.

Virtual DOM
Virtual DOM is nothing but a representation of actual DOM. It works like one-way data binding.
At every modification in the web application, the complete UI is re-rendered in virtual DOM
representation. Then, it analyses the difference between the new DOM (which is re-rendered)
and the representation of previous DOM. Once it gets completed, real DOM modifies the things
that changed. It saves memory and makes the application faster.

Simplicity
As we know, ReactJS uses JSX, which provides simplicity to the application and makes the code
understandable. ReactJS follows a component-based approach, which provides the reusability to
the code. It makes it easy to learn and use.

Components
ReactJS is made up of components, in which each component has its logic and controls. The
components are reusable that helps in maintaining the code when working on large scale
projects.

127
Performance
ReactJS has great performance. Because of this feature, ReactJS becomes much better to
compare to other frameworks. Behind this reason, there is a concept of managing virtual DOM.
The DOM is nothing but a cross-platform and programming API that deals with HTML, XML, and
XHTML. The DOM entirely exists in memory. Because of this, whenever we create a component,
we did not write them directly to the DOM; instead of this, we write virtual components that turn
into the DOM leads to smoother and faster performance.

How Does It Work?

While React is easier to learn for beginners with no prior JavaScript experience, the nitty gritty’s
of transpiling JSX code can often be overwhelming. This sets the tone for tools such as Babel and
Webpack. Webpack and Babel bundle together all the JavaScript files into a single file. Just like
how we use to include a link to the CSS and JS files in our HTML code, Webpack performs a similar
function eliminating the need for explicitly linking files.

I’m sure all of you use Facebook. Now, imagine Facebook being split into components,
each functionality is assigned to a specific component and each component produces some
HTML which is rendered as output by the DOM.

Facebook Components

 Search Bar

 Add Post

 Notifications Bar

 Feed Updates

 Profile Info

 Chat Window

To make things clear, refer to the image below.

128
React Environment Setup
This section will provide you the information about how to set up an environment for the
successful development of ReactJS application:

Pre-Requisite for ReactJS


1. NodeJS and NPM

2. React and React DOM

3. Webpack

4. Babel

There are two ways of installing the ReactJS:


1. Using npm command
2. By using create-react-app
By using npm command

Step 1: Install NodeJS. Go to https://nodejs.org


Step 2: Click on downloads.

129
Step 3: Install This Node.js
Step 4: Check the version by using the following command.

Step 5: Now, create a root folder in your desired directory with your desired name.

Step 6: Create a package.json file. This file is required for generating a module. Create this file
by using the command:
npm init –y

130
Step 7: Install React and its DOM Packages by using the npm command:
npm install react react-dom –save

Step 8: Install Webpack


Webpack is mainly used for module packaging, development, and production pipeline
automation.

For installing Webpack, we have to use the following command:

npm install webpack webpack-dev-server webpack-cli –save


In the above command, webpack-dev-server is used during development, webpack to create
production builds, and webpack-cli provides a set of commands.

Step 9: Install Babel.


Babel is simply a JavaScript compiler that is used for creating one source code to others. For
installing Babel, use the following command:

131
npm install babel-core babel-loader babel-preset-env babel-preset-react babel-webpack-
plugin –save-dev

Step 9: Create files. To complete the installation process, we need to add some files to the
project folder. The files are:
 index.html
 App.js
 main.js
 webpack.config.js
 .babelrc
We can manually create these files, or by using the command prompt. For creating files, use the
command prompt, and type the following command:

type nul > filename


Step 10: Now, Set Compiler, loader, and server for React Application
1. Configure Webpack

132
Add the code given below in the webpack.config.json to configure the Webpack. It sets the
development server to 8080 port. It is responsible for defining the loaders for processing the
file types that uses within your app and wrap up by adding plugins needed during our
development.

webpack.config.json

constpath=require('path');

constHtmlWebpackPlugin=require('html-webpack-plugin');

module.exports={

entry:'./main.js',

output:{

path:path.join(__dirname,'/bundle'),

filename:'index_bundle.js'

},

devServer:{

inline:true,

port:8080

},

module:{

rules:[

test:/\.jsx?$/,

exclude:/node_modules/,

133
use:{

loader:"babel-loader",

},

plugins:[

newHtmlWebpackPlugin({

template:'./index.html'

})

Now, open package.json file and delete “test” “echo \” Error: no test specified\” && exit
1″, which is inside “scripts” object, and add the commands start and build.

134
Delete which is shown in above image and add the following two:

1. “start”: “webpack-dev-server –mode development –open –hot”,


2. “build”: “webpack –mode production”
It is described in the following image:

135
 HTML webpack template for index.html
We have to add a custom template to generate index.html using the HtmlWeb-
packPlugin plugin. It enables us to a viewport tag for supporting mobile scaling of our app.
Add the following code to your index.html file.

index.html

<!DOCTYPEhtml>

<htmllang="en">

<head>

<metacharset="UTF-8">

<title>ReactApp</title>

</head>

<body>

<divid="app"></div>

<scriptsrc='index_bundle.js'></script>

</body>

</html>

 App.jsx and main.js

136
This is the app entry point i.e., the first react component. It will render Hello World.

Add the following code to your App.js file.

App.js

importReact,{Component}from'react';

classAppextendsComponent{

render(){

return(

<div>

<h1>HelloWorld</h1>

</div>

);

exportdefaultApp;

137
Now, we have to import this component and render it to the root App element so that we can
see it in the browser.

main.js
importReactfrom'react';

importReactDOMfrom'react-dom';

importAppfrom'./App.js';

ReactDOM.render(<App/>,document.getElementById('app'));

 Create .babelrc file


Add the following code to your .babelrc file.
.babelrc

"presets":[

"@babel/preset-env","@babel/preset-react"]

Now, run the server. For running the server, apply the following command in your command
prompt within the same folder in which all react files exist.

npm start
This command will show the port number, which requires an opening in the browser. After
opening it, you will get the following output:

138
By using the create-react-app command

Step 1: Install NodeJS. Go to https://nodejs.org


Step 2: Click on downloads.

Step 3: Install This Node.js


Step 4: Check the version by using the following command.

Step 5: Now Install NPM in your selected drive, by using the command: npm install –g create-
react-app

Step 6: Now create your own React project by using the command:
create-react-app your project name
It will take some time.

139
Step 7: Now move to your project folder by using: cd ‘your folder name.’

Step 8: Now write the command npm start

140
Then a webpage on your browser will be opened. This is the output of your React App.

If you want to change the above output, open the App.js file, which is located in the src
folder (src>>App.js), and make the changes that you want to see on the screen. Once you save
the file, the webpack will recompile the code, and the page will automatically refresh, then the
changes will be reflected on the screen.
For example:
The following image shows you the output after a change in the App.js file.

Now, open your project in the editor. I have Visual studio. You can see the project’s default
structure in the following image:

141
There are various files and folders in the root directory of the React Application. Some are
defined as follows:

1. node_modules: It includes React libraries and any other third party libraries if needed.
2. public: It contains the public assets of the application. It contains the file
name index.html where React will mount the application by default on the <div
id=”root”></div> element.
3. src: It contains several files like App.css, App.js, App.test.js, index.css, index.js, and
serviceWorker.js files. The App.js file will always be responsible for displaying the React output
screen.
4. package-lock.json: It automatically generates for any operations where the npm package
modifies either the package.json or the node_modules tree. It can’t be published. If it finds any
other place rather than the top-level package, then it will be ignored.
5. package.json: It contains various metadata for the project. It provides information to the
npm that allows identifying the project dependencies as well as the project.
6. README.md: It includes the React topics documentation.

142
React JSX
As we know, all of the React components include a render function. The Render function specifies
the HTML output of a React component. JSX is an acronym of JavaScript extension that allows
writing JavaScript code that looks like HTML. JSX is an HTML-like syntax used by react which
extends the ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code. The
syntax used by the preprocessors (i.e., transpilers like Babel) for transforming HTML-like syntax
into standard JavaScript objects that a JavaScript engine will parse.

It provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) within the
same file where you write your JavaScript code, and then preprocessor will transform these
expressions into actual JavaScript code. JSX tags also have a tag name, attributes, and children
just like XML/HTML.

Why use JSX?

 It is faster in comparison to JavaScript as it performs optimization during translation of


the code to JavaScript.

 Instead, the separation of technologies by putting markup and logic in separate files,
React has the components that contain both.

 It is type-safe because most of the errors are found at compile time.

 It makes template creation easy.

Nested Elements in JSX


If you want to use more than one element, you require wrapping it with one container element.
Here, the div is used as a container element that has three nested elements in it.

App.JSX

import React, { Component } from 'react';

class App extends Component{

143
render(){

return(

<div>

<h1>Hello World !!</h1>

<h2>This is TutorialandExample</h2><p>Website with the best tutorials.</p>

</div>

export default App;

JSX Attributes
The attributes in JSX with the HTML elements are same as the regular HTML. The naming
convention in JSX is in camelcase for attributes instead of standard naming convention of HTML
like class in HTML becomes className in JSX. This is because the class is reserved keyword in
JavaScript. There is also the use of custom attributes in JSX. We have to use data-prefix, for
custom attributes.
The example given below shows the use of custom attribute data-customAttr as an attribute for
the <p> tag.
For example:
import React, { Component } from 'react';

class App extends Component{

render(){

return(

144
<div>

<h1>Hello World !!</h1>

<h2>This is TutorialandExample</h2>

<p data-customAttr = "hello">Website with the best tutorials.</p>

</div>

);

export default App;

JavaScript Expressions

The expressions of JavaScript can be used inside of JSX. We have to wrap it with curly brackets {}.
The following example shows it more clearly.

Example:
import React, { Component } from 'react';

class App extends Component{

render(){

return(

<div>

<h1>{12+28}</h1>

<h1>Hello World !!</h1>

145
<h2>This is TutorialandExample</h2>

<p data-customAttr = {"hello"}>Website with the best tutorials.</p>

</div>

);

export default App;

There is not any use of if else statements inside JSX, we have to use conditional
(ternary) expressions. In the following example, the value of variable x equals to 1 so the
browser will give true, if we replace this value with some other value, it will give false.
Example: import React, { Component } from 'react';

class App extends Component{

render(){

var x=1;

return(

<div>

<h1>{x == 1 ? 'True!' : 'False'}</h1>

<h2>This is TutorialandExample</h2>

<p data-customAttr = {"hello"}>Website with the best tutorials.</p>

</div>

);

146
}

export default App;

JSX styling

React recommends using inline styles. To set inline styles, we require camelCase syntax. React
automatically appends px after the number value on specific elements.
The following example shows you the styling in JSX:

import React, { Component } from 'react';

class App extends Component{

render(){

var newStyle = {

fontSize: 90,

fontFamily: 'Times New Roman',

color: '#789067'

return(

<div>

<h1 style = {newStyle}>www.google.com</h1>

<h2>This is TutorialandExample</h2>

<p data-customAttr = {"hello"}>Website with the best tutorials.</p>

</div>

147
);

export default App;

JSX Comments
For writing comments, we have to put curly braces {}. The comments in JSX are begin with /* and
ends with */ as in the case of JSX expressions. Below example clarifies how to use comments in
JSX.
For example:
import React, { Component } from 'react';

class App extends Component{

render(){

var newStyle = {fontSize: 90,

fontFamily: 'Times New Roman',

color: '#789067'

return(

<div>

<h1 style = {newStyle}>www.google.com</h1>

<h2>This is TutorialandExample</h2>

<p data-customAttr = {"hello"}>Website with the best tutorials.</p>

{/* this is a comment of JSX*/

148
</div>

);

export default App;

React Components
Former, the developers used to write more than thousands of lines of code to develop a single-
page application. These applications follow the structure of traditional DOM, and it was very
challenging to make any change with them. And if any mistake found, it requires being search
manually in the entire application and update accordingly. The component-based approach is
introduced to resolve this issue. According to this approach, the complete application is divided
into a small logical group of code, which is known as components.

A component is considered as the core building block of a React application. It makes the task of
building UIs convenient. Every component resides in the same space, but works independently
from one another and merges all them in a parent component, which will be the final UI of the
application.

Every React component has its structure, methods as well as APIs. They can be reused as per the
requirements.

There are two types of components in ReactJS that are as follows:

1. Functional Components (Stateless Components).


2. Class Components (Stateful component).
Functional Components

149
The functional components are also known as stateless components because they do not hold
or manage state. Functional components are a way to write components that only includes a
render method and do not have their state. They simply are the JavaScript functions that might
or might not receive the data as parameters. We also can create a function that has props
(properties) as inputs and returns what should be rendered.
The example of Stateless components is as follows:

import React, { Component } from 'react';

class App extends React.Component {

render() {

return (

<div>

<First/>

<Second/>

</div>

);

class First extends React.Component {

render() {

return (

<div>

<h1>Stateless Components</h1>

</div>

150
);

class Second extends React.Component {

render() {

return (

<div>

<h2>www.tutorialandexample.com</h2>

<p>This website has several tutorials.</p>

</div>

);

export default App;

Output:

Class Components
Class components are also called as Stateful Components, because of holding or managing local
state. These components are more complex than stateless components. It requires you to extend
from React.

151
ReactJS Features
As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript
framework. It is crucial for the front-end ecosystem.

There are some of the crucial features of ReactJS that are mentioned as follows:

 JSX

 Components

 One-way data binding

 Virtual DOM

 Simplicity

 Performance

Let’s elaborate on these features:

JSX
JSX is an acronym of JavaScript XML. It is an extension of the JavaScript syntax. Its syntax is similar
to XML or HTML. This syntax is processed into JavaScript Calls of React Framework. It enhances
the ES6 so that the texts like HTML can co-exist with JavaScript react code. It is not mandatory to
use JSX, but it is advisable to use it in ReactJS.

152
One-Way Data Binding
ReactJS is designed in a manner that follows the unidirectional data flow or one-way Data
Binding. One-way data binding is advantageous as it provides better control throughout the
application. When the data flow in another direction, then the additional features are required
in it. It happens because the components are thought to be immutable, and the data within them
cannot be modified. The pattern Flux helps to keep data unidirectional. It provides more flexibility
to the application, which leads to increase efficiency.

153

You might also like