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

Angular 8 Notes

NPM is the default package manager for JavaScript and is used with Node.js, an open-source runtime environment for server-side applications. Angular, a TypeScript-based framework developed by Google, allows for the creation of dynamic web applications and includes features such as components, services, and directives. Single Page Applications (SPAs) enhance user experience by only updating parts of a page rather than reloading the entire page, making them more efficient.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Angular 8 Notes

NPM is the default package manager for JavaScript and is used with Node.js, an open-source runtime environment for server-side applications. Angular, a TypeScript-based framework developed by Google, allows for the creation of dynamic web applications and includes features such as components, services, and directives. Single Page Applications (SPAs) enhance user experience by only updating parts of a page rather than reloading the entire page, making them more efficient.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

NPM is a package manager for the JavaScript programming language.

It is
the default package manager for the JavaScript runtime environment

Node.js is an open source, cross-platform runtime environment for


developing server-side
and networking applications. Node.js applications are written in
JavaScript, and can be run
within the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules which
simplifies the
development of web applications using Node.js to a great extent.

Node.js is a server-side platform built on Google Chrome's JavaScript


Engine (V8 Engine)

What is Angular ?

Angular is an open source, TypeScript based frontend web application framework.


Angular has been released by Google’s Angular community. This tutorial starts with
the architecture of Angular ,setup simple project, data binding, then walks through
forms, templates, routing and explains about Angular new features. Finally, conclude
with step by step working example.

Prerequisites
Before proceeding with the various types of concepts given in this tutorial, we assume
that the readers have the basic knowledge on HTML, CSS and OOPS concepts. In
addition to this, it will be very helpful, if the readers have a sound knowledge on
TypeScript and JavaScript.

Angular is a client-side TypeScript based framework which is used


to create dynamic web applications. It is very similar to its previous
versions except having some extensive features.

What’s Single Page Application?

1
Single page application (SPA) is a single page (hence the name) where a
lot of information stays the same and only a few pieces need to be updated
at a time.

For example, when you browse through your email you’ll notice that not
much changes during navigation - the sidebar and header remain untouched
as you go through your inbox.

The SPA only sends what you need with each click, and your browser renders
that information. This is different to a traditional page load where the
server re-renders a full page with every click you make and sends it to
your browser.

This piece by piece, client side method makes load time must faster for
users and makes the amount of information a server has to send a lot less
and a lot more cost efficient.

Note: Dynamic web applications are simply dynamic websites


i.e. www.gmail.com, www.yahoo.com, etc. which has tendency to change data/information
with respect to 3 parameters:

o Time-to-time (eg. news update webs applications)


o Location-to-location (eg. Weather-report web applications)
o User-to-user (eg. Gmail, Facebook type applications)

You can see how to upgrade Angular CLI to version . Click Here

New Features of Angular


The Angular community has released its latest version Angular with an
impressive list of changes and improvements including the much awaited Ivy
compiler as an opt-in feature.

These are the most prominent features of Angular :

o Angular supports TypeScript 3.4


o Angular supports Web Workers
o The new compiler for Angular is Ivy Rendering Engine
o Angular provides dynamic imports for lazy-loaded modules.
o Improvement of ngUpgrade

2
TypeScript 3.4
Angular supports TypeScript 3.4 and it is required to run your Angular
project. So you have to upgrade your TypeScript version to 3.4.

Prerequisite for Angular tutorial


o You must have installed Node.js version > 10. NPM will be updated also
because it will be used by default. Here, I am using Node version 12.4.0
o You must have installed MongoDB on your system. You can see how to install
MongoDB. Click here...

Workflow of Angular Tutorial


Here, we will create two separate projects:

One for front end (in Angular) and one for backend (in Node.js |
Express | MongoDB). We will also create a backend API which will be used
by frontend.

Here, we use the following technologies:

o Node: 12.4.0
o Angular CLI: .0.2
o NPM: v12.4.0
o To check Node and Angular CLI version, use ng --
version command.
o To check npm version, use node -v command.

Angular Architecture
The basic building blocks of an Angular application are NgModules, which
provide a compilation context for components. NgModules collect related
code into functional sets; an Angular app is defined by a set of NgModules.

3
An app always has at least a root module that enables bootstrapping, and
typically has many more feature modules.

o Components define views, which are sets of screen elements that Angular
can choose among and modify according to your program logic and data.
o Components use services, which provide specific functionality not directly
related to views. Service providers can be injected into components as
dependencies, making your code modular, reusable, and efficient.

Key parts of Angular Architecture:

Create an Angular project


Let's create an Angular project by using the following command:

1. ng new angularproject

Here, angularproject is the name of the project.

4
Install Bootstrap 4 CSS framework
Use the following command to install bootstrap in your
project.npm install bootstrap --save

Now, add the following code inside the angular.json file.

1. "styles": [
2. "src/styles.css",

5
3. "./node_modules/bootstrap/dist/css/bootstrap.min.css"
4. ],

The above CSS is used that we can use the bootstrap classes inside any file.

6
Start the Angular development server using the following
command.ng serve

The server starts at the http://localhost:4200/

Angular Components
In Angular , Components and services both are simply classes with
decorators that mark their types and provide metadata which guide Angular
to do things.

Every Angular application always has at least one component known as root
component that connects a page hierarchy with page DOM. Each component
defines a class that contains application data and logic, and is associated
with an HTML template that defines a view to be displayed in a target
environment.

Metadata of Component class

o The metadata for a component class associates it with a template that


defines a view. A template combines ordinary HTML with Angular directives
and binding markup that allow Angular to modify the HTML before rendering
it for display.
o The metadata for a service class provides the information Angular needs to
make it available to components through dependency injection (DI).

7
Modules
Angular NgModules are different from other JavaScript modules. Every
Angular app has a root module known as AppModule. It provides the
bootstrap mechanism that launches the application.

Generally, every Angular app contains many functional modules.

Some important features of Anngular Modules:

o Angular NgModules import the functionalities form other NgModules just like
other JavaScript modules.
o NgModules allow their own functionality to be exported and used by other
NgModules. For example, if you want to use the router service in your app,
you can import the Router NgModule.

Template, Directives and Data Binding


In Angular , a template is used to combine HTML with Angular Markup and
modify HTML elements before displaying them. Template directives provide

8
program logic, and binding markup connects your application data and the
DOM.

There are two types of data binding:

1. Event Binding: Event binding is used to bind events to your app and
respond to user input in the target environment by updating your application
data.

2. Property Binding: Property binding is used to pass data from


component class and facilitates you to interpolate values that are computed
from your application data into the HTML.

Services and Dependency Injection


In Angular , developers create a service class for data or logic that isn't
associated with a specific view, and they want to share across components.

Dependency Injection (DI) is used to make your component classes lean


and efficient. DI doesn't fetch data from the server, validate user input, or
log directly to the console; it simply renders such tasks to services.

Routing3
In Angular , Router is an NgModule which provides a service that facilitates
developers to define a navigation path among the different application states
and view hierarchies in their app.

It works in the same way as a browser's navigation works. i.e.:

o Enter a URL in the address bar and the browser will navigate to that
corresponding page.
o Click the link on a page and the browser will navigate to a new page.
o Click the browser's back or forward buttons and the browser will navigate
backward or forward according to your seen history pages.

Angular Directives
The Angular directives are used to manipulate the DOM. By using Angular
directives, you can change the appearance, behavior or a layout of a DOM
element. It also helps you to extend HTML.

9
Angular directives can be classified in 3 categories based on how
they behave:

o Component Directives
o Structural Directives
o Attribute Directives

Component Directives: Component directives are used in main class. They


contain the detail of how the component should be processed, instantiated
and used at runtime.

Structural Directives: Structural directives start with a * sign. These


directives are used to manipulate and change the structure of the DOM
elements. For example, *ngIf directive, *ngSwitch directive, and *ngFor
directive.

o *ngIf Directive: The ngIf allows us to Add/Remove DOM Element.


o *ngSwitch Directive: The *ngSwitch allows us to Add/Remove DOM
Element. It is similar to switch statement of C#.
o *ngFor Directive: The *ngFor directive is used to repeat a portion of
HTML template once per each item from an iterable list (Collection).

10
Attribute Directives: Attribute directives are used to change the look and
behavior of the DOM elements. For example: ngClass directive, and ngStyle
directive etc.

o ngClass Directive: The ngClass directive is used to add or remove


CSS classes to an HTML element.
o ngStyle Directive: The ngStyle directive facilitates you to modify the
style of an HTML element using the expression. You can also use
ngStyle directive to dynamically change the style of your HTML
element.

Angular ngIf Directive


The ngIf Directives is used to add or remove HTML Elements according to the
expression. The expression must return a Boolean value. If the expression is
false then the element is removed, otherwise element is inserted. It is similar
to the ng-if directive of AngularJS.

ngIf Syntax
1. <p *ngIf="condition">
2. condition is true and ngIf is true.
3. </p>
4. <p *ngIf="!condition">
5. condition is false and ngIf is false.
6. </p>

The *ngIf directive form with an "else" block


1. <div *ngIf="condition; else elseBlock">
2. Content to render when condition is true.
3. </div>
4. <ng-template #elseBlock>
5. Content to render when condition is false.
6. </ng-template>

The ngIf directive does not hide the DOM element. It removes the entire
element along with its subtree from the DOM. It also removes the
corresponding state freeing up the resources attached to the element.

11
The *ngIf directive is most commonly used to conditionally show an inline
template. See the following example:

1. @Component({
2. selector: 'ng-if-simple',
3. template: `
4. <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
5. show = {{show}}
6. <br>
7. <div *ngIf="show">Text to show</div>
8. `
9. })
10.export class NgIfSimple {
11. show: boolean = true;
12.}

Same template example with else block


1. @Component({
2. selector: 'ng-if-else',
3. template: `
4. <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
5. show = {{show}}
6. <br>
7. <div *ngIf="show; else elseBlock">Text to show</div>
8. <ng-template #elseBlock>Alternate text while primary text is hidden</ng-
template>
9. `
10.})
11.export class NgIfElse {
12. show: boolean = true;
13.}

Angular *ngFor Directive


12
The *ngFor directive is used to repeat a portion of HTML template once per
each item from an iterable list (Collection). The ngFor is an Angular structural
directive and is similar to ngRepeat in AngularJS. Some local variables like
Index, First, Last, odd and even are exported by *ngFor directive.

Syntax of ngFor
See the simplified syntax for the ngFor directive:

1. <li *ngFor="let item of items;"> .... </li>

How to use ngFor Directive?


To Use ngFor directive, you have to create a block of HTML elements, which
can display a single item of the items collection. After that you can use the
ngFor directive to tell angular to repeat that block of HTML elements for each
item in the list.

Example for *ngFor Directive


First, you have to create an angular Application. After that open the
app.component.ts and add the following code.

The following Code contains a list of Top 3 movies in a movies array. Let's
build a template to display these movies in a tabular form.

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


2. @Component({
3. selector: 'movie-app',
4. templateUrl:'./app/app.component.html',
5. styleUrls:['./app/app.component.css']
6. })
7. export class AppComponent
8. {
9. title: string ="Top 10 Movies" ;
10. movies: Movie[] =[
11. {title:'Zootopia',director:'Byron Howard, Rich Moore',cast:'Idris Elba, Ginnifer G
oodwin, Jason Bateman',releaseDate:'March 4, 2016'},

13
12. {title:'Batman v Superman: Dawn of Justice',director:'Zack Snyder',cast:'Ben A
ffleck, Henry Cavill, Amy Adams',releaseDate:'March 25, 2016'},
13. {title:'Captain America: Civil War',director:'Anthony Russo, Joe Russo',cast:'Sca
rlett Johansson, Elizabeth Olsen, Chris Evans',releaseDate:'May 6, 2016'},
14. {title:'X-Men: Apocalypse',director:'Bryan Singer',cast:'Jennifer Lawrence, Olivi
a Munn, Oscar Isaac',releaseDate:'May 27, 2016'},
15. ]
16.}
17.class Movie {
18. title : string;
19. director : string;
20. cast : string;
21. releaseDate : string;
22.}

Now, open the app. component.html and add the following code:

1. <div class='panel panel-primary'>


2. <div class='panel-heading'>
3. {{title}}
4. </div>
5. <div class='panel-body'>
6. <div class='table-responsive'>
7. <table class='table'>
8. <thead>
9. <tr>
10. <th>Title</th>
11. <th>Director</th>
12. <th>Cast</th>
13. <th>Release Date</th>
14. </tr>
15. </thead>
16. <tbody>
17. <tr *ngFor="let movie of movies;">
18. <td>{{movie.title}}</td>

14
19. <td>{{movie.director}}</td>
20. <td>{{movie.cast}}</td>
21. <td>{{movie.releaseDate}}</td>
22. </tr>
23. </tbody>
24. </table>
25. </div>
26. </div>
27.</div>

When you run the application, It will show the movies in tabular form.

Angular ngSwitch Directive


In Angular , ngSwitch is a structural directive which is used to Add/Remove
DOM Element. It is similar to switch statement of C#. The ngSwitch directive
is applied to the container element with a switch expression.

Syntax of ngSwitch
1. <container_element [ngSwitch]="switch_expression">
2. <inner_element *ngSwitchCase="match_expresson_1">...</inner_element>
3. <inner_element *ngSwitchCase="match_expresson_2">...</inner_element>
4. <inner_element *ngSwitchCase="match_expresson_3">...</inner_element>
5. <inner_element *ngSwitchDefault>...</element>
6. </container_element>

ngSwitchCase
In Angular ngSwitchCase directive, the inner elements are placed inside the
container element. The ngSwitchCase directive is applied to the inner
elements with a match expression. Whenever the value of the match
expression matches the value of the switch expression, the corresponding
inner element is added to the DOM. All other inner elements are removed
from the DOM

15
If there is more than one match, then all the matching elements are added
to the DOM.

ngSwitchDefault
You can also apply the ngSwitchDefault directive in Angular . The element
with ngSwitchDefault is displayed only if no match is found. The inner
element with ngSwitchDefault can be placed anywhere inside the container
element and not necessarily at the bottom. If you add more than one
ngSwitchDefault directive, all of them are displayed.

Any elements placed inside the container element, but outside the
ngSwitchCase or ngSwitchDefault elements are displayed as it is.

ngSwitch Directive Example


Use the following code in app.component.ts file of your application:

1. class item {
2. name: string;
3. val: number;
4. }
5. export class AppComponent
6. {
7. items: item[] = [{name: 'One', val: 1}, {name: 'Two', val: 2}, {name: 'Three', val:
3}];
8. selectedValue: string= 'One';
9. }

Use the following code in the app.component.html file of your


application:

1. <select [(ngModel)]="selectedValue">
2. <option *ngFor="let item of items;" [value]="item.name">{{item.name}}</
option>
3. </select>
4. <div class='row' [ngSwitch]="selectedValue">
5. <div *ngSwitchCase="'One'">One is Pressed</div>
6. <div *ngSwitchCase="'Two'">Two is Selected</div>

16
7. <div *ngSwitchDefault>Default Option</div>
8. </div>

The ngIf is an Angular Structural Directive, which allows us to add/remove


DOM Element based on some condition. In this Tutorial let us look at the
syntax of ngIf.

ng-template is an Angular element used to render HTML templates. We use


ng-template with angular *ngIf directive to display else template

app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title: string = 'ngIf Example' ;
showMe: boolean;
}
===============================

<h1>Simple example of ngIf </h1>

<div class="row">
Show <input type="checkbox" [(ngModel)]="showMe" />
</div>

<h1>ngIf </h1>

<p *ngIf="showMe">
ShowMe is checked
</p>
<p *ngIf="!showMe">
ShowMe is unchecked
</p>

<h1>ngIf Else</h1>

<p *ngIf="showMe; else elseBlock1">


ShowMe is checked
</p>

17
<ng-template #elseBlock1>
<p>ShowMe is unchecked Using elseBlock</p>
</ng-template>

<h1>ngIf then else</h1>

<p *ngIf="showMe; then thenBlock2 else elseBlock2">


This is not rendered
</p>

<ng-template #thenBlock2>
<p>ShowMe is checked Using thenblock</p>
</ng-template>

<ng-template #elseBlock2>
<p>ShowMe is unchecked Using elseBlock</p>
</ng-template>

<h1>using hidden </h1>

<p [hidden]="showMe">
content to render, when the condition is true using hidden property
binding
</p>

<p [hidden]="!showMe">
content to render, when the condition is false. using hidden property
binding
</p>

Data Binding in Angular


Data binding is the core concept of Angular and used to define the
communication between a component and the DOM. It is a technique to link
your data to your view layer. In simple words, you can say that data binding
is a communication between your typescript code of your component and
your template which user sees. It makes easy to define interactive
applications without worrying about pushing and pulling data.

Data binding can be either one-way data binding or two-way data binding.

18
One-way databinding
One way databinding is a simple one way communication where HTML
template is changed when we make changes in TypeScript code.

Or

In one-way databinding, the value of the Model is used in the View (HTML
page) but you can't update Model from the View. Angular Interpolation /
String Interpolation, Property Binding, and Event Binding are the example of
one-way databinding.

Two-way databinding
In two-way databinding, automatic synchronization of data happens between
the Model and the View. Here, change is reflected in both components.
Whenever you make changes in the Model, it will be reflected in the View
and when you make changes in View, it will be reflected in Model.

This happens immediately and automatically, ensures that the HTML


template and the TypeScript code are updated at all times.

Angular provides four types of data binding and they are different on the way
of data flowing.

o String Interpolation
o Property Binding
o Event Binding
o Two-way binding

19
String interpolation
String Interpolation is a one-way databinding technique which is used to
output the data from a TypeScript code to HTML template (view). It uses the
template expression in double curly braces to display the data from the
component to the view.

For example:

{{ data }}

String interpolation adds the value of a property from the component:

Syntax:

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


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

Learn more about String Interpolation: Click Here

Property Binding
Property Binding is also a one-way data binding technique. In property
binding, we bind a property of a DOM element to a field which is a defined
property in our component TypeScript code.

For example:

<img [src]="imgUrl"/>

Syntax:

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

Open app.componnt.ts file and add the following code:

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


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

20
title = "Data binding using Property Binding";
imgUrl="https://static.angular.com/tutorial/angular7/images/angular-7-
logo.png";

Property Binding in Angular 8


Now, open app.component.html and use the following code for property
binding:

<h2>{{ title }}</h2> <!-- String Interpolation -->


<img [src]="imgUrl" /> <!-- Property Binding -->

Learn more about Property Binding: Click Here

Event Binding
In Angular , event binding is used to handle the events raised from the DOM
like button click, mouse move etc. When the DOM event happens (eg. click,
change, keyup), it calls the specified method in the component. In the
following example, the cookBacon() method from the component is called
when the button is clicked:

For example:

1. <button (click)="cookBacon()"></button>

Learn more about Event Binding: Click Here

Two-way Data Binding


We have seen that in one-way data binding any change in the template
(view) were not be reflected in the component TypeScript code. To resolve
this problem, Angular provides two-way data binding. The two-way binding
has a feature to update data from component to view and vice-versa.

21
In two way data binding, property binding and event binding are combined
together.

Syntax:

1. [(ngModel)] = "[property of your component]"

Note: For two way data binding, we have to enable the ngModel directive. It depends upon
FormsModule in angular/forms package, so we have to add FormsModule in imports[] array
in the AppModule.

Two way Data Binding in Angular


We have seen that in one-way data binding any change in the template
(view) were not be reflected in the component TypeScript code. To resolve
this problem, Angular provides two-way data binding. The two-way binding
has a feature to update data from component to view and vice-versa.

In two-way databinding, automatic synchronization of data happens between


the Model and the View. Here, change is reflected in both components.
Whenever you make changes in the Model, it will be reflected in the View
and when you make changes in View, it will be reflected in Model.

This happens immediately and automatically, ensures that the HTML


template and the TypeScript code are updated at all times.

In two way data binding, property binding and event binding are
combined together.

Syntax:
1. [(ngModel)] = "[property of your component]"

22
Note: For two way data binding, we have to enable the ngModel directive. It depends upon
FormsModule in angular/forms package, so we have to add FormsModule in imports[] array
in the AppModule.

Let's take an example to understand it better.

Open your project's app.module.ts file and use the following code:

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


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

23
app.component.ts file:

1. import { Component } from "@angular/core";


2. @Component({
3. selector: "app-root",
4. templateUrl: "./app.component.html",
5. styleUrls: ["./app.component.css"]
6. })
7. export class AppComponent {
8. fullName: string = "Hello Angular";
9. }

24
app.component.html file:

1. <h2>Two-way Binding Example</h2>


2. <input [(ngModel)]="fullName" /> <br/><br/>
3. <p> {{fullName}} </p>

25
Now, start your server and open local host browser to see the result.

Output:

26
You can check it by changing textbox value and it will be updated in
component as well.

For example:

27
Property Binding in Angular
Property Binding is also a one-way data binding technique. In property
binding, we bind a property of a DOM element to a field which is a defined
property in our component TypeScript code. Actually Angular internally
converts string interpolation into property binding.

For example:

<img [src]="imgUrl" />

Property binding is preferred over string interpolation because it has shorter


and cleaner code String interpolation should be used when you want to
simply display some dynamic data from a component on the view between
headings like h1, h2, p etc.

Note: String Interpolation and Property binding both are one-way binding. Means, if field
value in the component changes, Angular will automatically update the DOM. But any
changes in the DOM will not be reflected back in the component.

Property Binding Example


Open app.componnt.ts file and add the following code:

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


2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. title = "Data binding using Property Binding";
9. imgUrl="https://static.angular.com/tutorial/angular7/images/angular-7-logo.png";
10.}

28
Now, open app.component.html and use the following code for property
binding:

1. <h2>{{ title }}</h2> <!-- String Interpolation -->


2. <img [src]="imgUrl" /> <!-- Property Binding -->

29
Run the ng serve command and open local host to see the result.

Output:

String Interpolation in Angular


String Interpolation is a one-way databinding technique which is used to
output the data from a TypeScript code to HTML template (view). It uses the
template expression in double curly braces to display the data from the

30
component to the view. String interpolation adds the value of a property
from the component.

For example:

{{ data }}

We have already created an Angular project using Angular CLI.

See: How to create Angular project. Click Here

Here, we are using the same project for this example.

Open app.component.ts file and use the following code within the file:

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


2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. title = 'Data binding example using String Interpolation';
9. }

31
Now, open app.component.html and use the following code to see string
interpolation.

1. <h2>
2. {{ title }}
3. </h2>

32
Now, open Node.js command prompt and run the ng serve command to see
the result.

Output:

33
String Interpolation can be used to resolve some other expressions too. Let's
see an example.

Example:
Update the app.component.ts file with the following code:

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


2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. title = 'Data binding example using String Interpolation';
9. numberA: number = 10;
10. numberB: number = 20;
11. }

app.component.html:

1. <h2>Calculation is : {{ numberA + numberB }}</h2>

34
Output:

You can use the same application in another way:

App.component.ts:

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


2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. title = 'Data binding example using String Interpolation';
9. numberA: number = 10;
10. numberB: number = 20;
11. addTwoNumbers() {
12. return this.numberA + this.numberB;
13. }
14.}

35
App.component.html:

1. <h2>Calculation is : {{ numberA + numberB }}</h2>

Event Binding in Angular


In Angular , event binding is used to handle the events raised from the DOM
like button click, mouse move etc. When the DOM event happens (eg. click,
change, keyup), it calls the specified method in the component. In the
following example, the cookBacon() method from the component is called
when the button is clicked:

36
For example:

1. <button (click)="cookBacon()"></button>

Event Binding Example


Let's take a button in the HTML template and handle the click event of this
button. To implement event binding, we will bind click event of a button with
a method of the component.

Now, open the app.component.ts file and use the following code:

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


2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. onSave($event){
9. console.log("Save button is clicked!", $event);
10. }
11.}

37
app.component.html:

1. <h2> Event Binding Example</h2>


2. <button (click)="onSave($event)">Save</button> <!--Event Binding-->

38
Output:

39
Click on the "Save" button and open console to see result.

Now, you can see that the "Save" button is clicked.

Event Bubbling
Event bubbling is used to specify an order in which event handlers are called
when one element is nested inside a second element, and both elements
have registered a listener for the same event (i.e. click).

Let's see the above button example. Here, I have used a div wrapper around
the button in component HTML and div has also a click event handler. It is
only to show some message if div is clicked.

Use the following code in app.component.ts file:

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


2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. onSave($event){
9. console.log("Save button is clicked!", $event);
10. }
11. onDivClick(){

40
12. console.log("DIV is clicked!");
13. }
14.}

app.component.html:

1. <h2>Event Bubbling Example</h2>


2. <!-- Event Bubbling -->
3. <div (click)="onDivClick()">
4. <button (click)="onSave($event)">Save</button> <!-- Event Binding -->
5. </div>

41
Output:

Click on the "Save" button and open console to see result.

42
Here, you can see that your div message is also occurred. This is all due to
event bubbling where you have specified onDivClick button.

43
Output:

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

In Angular , there are 2 approaches to handle user's input through forms:

o Reactive forms
o Template-driven forms

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

Reactive Forms vs. Template-driven Forms


Both Reactive forms and Template-driven forms manage and process data
differently. Each offers different advantages.

44
Reactive Forms
o Reactive forms are more robust.
o Reactive forms are more scalable, reusable, and testable.
o They are most preferred to use if forms are a key part of your application, or
your application is already built using reactive patterns. In both cases,
reactive forms are best to use.

Template-driven Forms
o Template-driven forms are best if you want to add a simple form to your
application. For example: email list signup form.
o Template-driven forms are easy to use in the application but they are not as
scalable as Reactive forms.
o Template-driven forms are mainly used if your application's requires a very
basic form and logic. It can easily be managed in a template.

Angular Form Example


Let's understand the Angular form by creating a form example. Here, we use
Angular reactive form.

Follow the steps given below:

o Create an Angular form app named angularfrom and run the server by
using the following commands.

1. ng new angularform
2. cd angularform
3. ng serve

45
o Install the Bootstrap 4 using the following command.

46
1. npm install bootstrap --save

Now, include the bootstrap 4 inside the angular.json file inside styles array.

1. "styles": [
2. "./node_modules/bootstrap/dist/css/bootstrap.min.css",
3. "src/styles.css"
4. ],

o Register the Reactive Forms Module

Use the reactive forms by importing ReactiveFormsModule from the


@angular/forms package and add it to your app.module.ts file's imports
array.

So use the following code inside the app.module.ts file.

1. // app.module.ts
2. import { BrowserModule } from '@angular/platform-browser';
3. import { NgModule } from '@angular/core';
4.
5. import { AppRoutingModule } from './app-routing.module';
6. import { AppComponent } from './app.component';
7. import { ReactiveFormsModule } from '@angular/forms';
8.

47
9. @NgModule({
10. declarations: [
11. AppComponent
12. ],
13. imports: [
14. BrowserModule,
15. AppRoutingModule,
16. ReactiveFormsModule
17. ],
18. providers: [],
19. bootstrap: [AppComponent],
20.})
21.export class AppModule { }

48
o Add FormControl class register the control into the template and update the
FormControl value

The FormControl class is the fundamental building block when using the
reactive forms. So if you want to register the single form control, you need to
import the FormControl class into your component and create the new
instance of a form control to save as the class property.

Now, modify the app.component.ts file.

1. // app.component.ts
2. import { Component } from '@angular/core';
3. import { FormControl } from '@angular/forms';
4. @Component({
5. selector: 'app-root',
6. templateUrl: './app.component.html',
7. styleUrls: ['./app.component.css']
8. })
9. export class AppComponent {
10. email = new FormControl('');
11. updateEmail() {
12. this.email.setValue('[email protected]');
13. }
14.}

49
Also, update the view app.component.html file.

1. <div class="container">
2. <div class="form-group">
3. <label>
4. Email:
5. </label>
6. <input type="text" [formControl]="email" />
7. </div>
8. <div class="form-group">
9. <button (click)="updateEmail()" class="btn btn-dark">Update Email</button>

10. </div>
11. <p>
12. Value: {{ email.value }}

50
13. </p>
14.</div>

Now, save your code and start the server.

Output:

Enter any email id and you will see the result in the value.

51
When you click on the "Update Email" button, it will update the email id as
we saved in the template file.

Angular vs React

52
Angular and React both are related to JavaScript but there are a lot of
differences between them. Here, we are going to compare both of them and
also explain their similarities, differences, advantages and disadvantages
etc.

Comparison Angular React


Index

History Angular is a TypeScript based JavaScript React is not a framework. It is


framework. It is written in JavaScript library developed a
TypeScript. Angular is developed and maintained by Facebook a
maintained by Google and known as a described as "a JavaScript library
"Superheroic JavaScript MVWFramework". building user interfaces. React w
Angular is a complete rewrite of AngularJS. released in 2013 and after that it
AngularJS was released in 2010 and it being used at Facebook.
takes almost 6 years to release its second
version Angular 2 (a complete rewrite).
The latest version of Angular is Angular
now. Google AdWords which is one of the
important project of Google uses Angular,
so it is going to be big in upcoming years.

Architectur Angular is a full MVC (Model, View, and React is a simple JavaScript libra
e Controller) framework. (just the View) but it gives you mu
Angular is considered a framework more freedom. React facilitates y
because it provides strong facilities like to choose your own librari
how to structure your application. In Most prominent features of React:
Angular, you don't need to decide routing
libraries. o React uses JSX, an XML-l
Most prominent features of Angular: language built on top
JavaScript instead of clas
o Provides templates, based on an
templates.
extended version of HTML.
o XSS protection.
o Provides XSS protection.
o No dependency injection.
o Provides Dependency injection.
o Fetch for Ajax requests.
o Provides Ajax requests by
@angular/HTTP. o Utilities for unit-testi
components.
o @angular/router for Routing.

53
React also provides some popu
o Component CSS encapsulation. libraries to add functionalities:
o Utilities for unit-testing components. o React-router for routing.
o @angular/forms for building forms. o Redux or MobX for sta
management.
o Enzyme for additional testi
utilities.

Used DOM Angular uses regular DOM. The regular React uses virtual DOM wh
DOM updates the entire tree structure of makes it amazing fast. It was s
HTML tags. It doesn't make difference in a the most prominent feature of Rea
simple real app but if you are dealing with when it was release
large amount of data requests on the same It updates only the specific part with
page (and the HTML block is replaced for a block of HTML codes. The virtu
every page request), it affects the DOM looks only at the differenc
performance as well as the user's between the previous and curre
experience. HTML and changes only that p
which is required to be updated.

Used Angular uses enhanced HTML templates React uses UI templates and inli
Templates with Angular directives i.e. "ng-if" or "ng- JavaScript logic together which w
for" etc. It is quite difficult because you not done by any company befo
have to learn its specific syntax. This is called JSX. React us
component which contains both t
markup AND logic in the same fi
React also uses an XML-like langua
which facilitates developers to wr
markup directly in their JavaScr
code. JSX is a big advantage
development, because you ha
everything in one place, and co
completion and compile-time chec
work better.

Data Angular provides two-way data binding. React provides one-way data bindin
Binding When you change the model state, then In React first the model state
the UI element changes. In Angular, if you updated, and then it renders t
change the UI element, then the change in the UI element. When y
corresponding model state changes as change the UI element, the mod

54
well. Additionally, if you change the model state does not change.
state, then the UI element changes.

TypeScript Angular is written in TypeScript, so you React uses JavaScript which is


vs must be comfortable with TypeScript dynamically-typed language, so y
JavaScript before using Angular. don't have to define the variabl
type. It makes it easy to use.

Scalability Angular is easy to scale. React is more scalable than Angular

Speed Angular is fast as compared to old React is faster than Angular.


technologies but React is faster than
Angular.

Size The size of Angular is large, so it takes The size of React is smaller th
longer load time and performance on Angular, so it is a little bit faster.
mobile.

Company
o Google o Facebook
Using
o Nike o Airbnb
o Forbes o Uber
o Upwork o Netflix
o General Motors o Instagram
o HBO o WhatsApp
o Sony etc. o Dropbox etc.

Similarities
o Angular and React both are available under MIT license.
o Both Angular and React are component based.

55
Angular Pipes
In Angular 1, filters are used which are later called Pipes onwards Angular2.
In Angular 7, it is known as pipe and used to transform data. It is denoted by
symbol |

Syntax:
1. {{title | uppercase}}

Pipe takes integers, strings, arrays, and date as input separated with |. It
transforms the data in the format as required and displays the same in the
browser.

Let's see an example using pipes. Here, we display the title text in upper and
lower case by using pipes.

Example:
Define a variable named "title" in component.ts file.

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


2.
3. @Component({
4. selector: 'app-root',
5. templateUrl: './app.component.html',
6. styleUrls: ['./app.component.css']
7. })
8. export class AppComponent {
9. title = 'my-first-app';
10.}

Use the pipe symbol in component.html file:

1. <h1>
2. {{ title | uppercase }} <br/></h1>
3. <h1>
4. {{ title | lowercase }} <br/></h1>

56
Output:

Run ng serve and see the result. You will see the following result.

Here, you can see that pipes have changed the tittle in upper and lowercase.

Angular Built-in Pipes


Angular provides some built-in pipes:

o Lowercasepipe
o Uppercasepipe
o Datepipe
o Currencypipe
o Jsonpipe
o Percentpipe
o Decimalpipe
o Slicepipe

57
You have seen the lowercasepipe and uppercasepipe examples. Now, let's
take some examples to see how the other pipes work.

Example:
Define the required variables in component.ts file.

component.ts file:

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


2.
3. @Component({
4. selector: 'app-root',
5. templateUrl: './app.component.html',
6. styleUrls: ['./app.component.css']
7. })
8. export class AppComponent {
9. title = 'my-first-app';
10. todaydate = new Date();
11. jsonval = {name: 'Alex', age: '25', address:{a1: 'Paris', a2: 'France'}};
12. months = ['Jan', 'Feb', 'Mar', 'April', 'May', 'Jun',
13. 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
14.}

Use the different built-in pipe symbols in component.html file:

component.html file:

1. <div style = "width:100%;">


2. <div style = "width:40%;float:left;border:solid 1px black;">
3. <h1>Uppercase Pipe</h1>
4. <b>{{title | uppercase}}</b><br/>
5. <h1>Lowercase Pipe</h1>
6. <b>{{title | lowercase}}</b>
7. <h1>Currency Pipe</h1>
8. <b>{{659.23 | currency:"USD"}}</b><br/>

58
9. <b>{{659.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign
of the currency.
10. <h1>Date pipe</h1>
11. <b>{{todaydate | date:'d/M/y'}}</b><br/>
12. <b>{{todaydate | date:'shortTime'}}</b>
13. <h1>Decimal Pipe</h1>
14. <b>{{ 454.77714 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for i
ntegers to be displayed.
15. </div>
16. <div style = "width:40%;float:left;border:solid 1px black;">
17. <h1>Json Pipe</h1>
18. <b>{{ jsonval | json }}</b>
19. <h1>Percent Pipe</h1>
20. <b>{{00.54565 | percent}}</b>
21. <h1>Slice Pipe</h1>
22. <b>{{months | slice:2:6}}</b>
23. // here 2 and 6 refers to the start and the end index
24. </div>
25.</div>

Output:

You can see the use of all built-in pipes here:

59
How to create a custom pipe?
To create a custom pipe, create a new ts file and use the code according to
the work you have to do. You have to import Pipe, PipeTransform from
Angular/Core. Let's create a sqrt custom pipe.

sq.pipe.ts file:

1. import {Pipe, PipeTransform} from '@angular/core';


2. @Pipe ({
3. name : 'sq'
4. })
5. export class sqPipe implements PipeTransform {
6. transform(val : number) : number {

60
7. return Math.sqrt(val);
8. }
9. }

app.component.ts file:
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Welcome Custom Pipes';
}

Now, it's turn to make changes in the app.module.ts. Create a class named
as SqPipe. This class will implement the PipeTransform. The transform
method defined in the class will take argument as the number and will return
the number after taking the square root.

As, we have created a new file so, we need to add the same in
app.module.ts.

Module.ts file:

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


2. import { NgModule } from '@angular/core';
3. import { AppComponent } from './app.component';
4. import { sqPipe } from './sq.pipe';
5. @NgModule({
6. declarations: [
7. sqPipe,
8. AppComponent,
9. ],
10. imports: [
11. BrowserModule

61
12. ],
13. providers: [],
14. bootstrap: [AppComponent]
15.})
16.export class AppModule { }

Now, use sq pipe in component.html file.

component.html file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<h1>Example Of custom Pipe</h1>
<b>Square root of 625 is {{625 | sq}}</b><br>
<b>Square root of 169 is {{169 | sq}}</b>
</div>
</body>
</html>

Output:

Example Of custome Pipe


Square root of 625 is 25
Square root of 169 is 13

Difference between Angular and AngularJS

Angular: It is a popular open-source Typescript framework created by


Google for developing web applications. Front-end developers use

62
frameworks like Angular or React for presenting and manipulating data
efficiently. Updated Angular is much more efficient compared to the older
version of Angular, especially core functionality was moved to different
modules. That’s why it becomes so much fast and smooth compare to the
older one. Newly added angular CLI. With that package, you can create
scaffolding of your Angular project

Angular JS: AngularJs is a Javascript open-source front-end framework that


is mainly used to develop single-page web applications(SPAs). It is a
continuously growing and expanding framework which provides better ways
for developing web applications. It changes the static HTML to dynamic
HTML. It’s features like dynamic binding and dependency injection
eliminates the need for code that we have to write otherwise.AngularJs is
rapidly growing and because of this reason, we have different versions of
AngularJs with the latest stable being 1.7.7. It is also important to note
that Angular is different from AngularJs. It is an open-source project
which can be freely used and changed by anyone. It extends HTML attributes
with Directives, and data is bound with HTML.

Architecture:

Angular JS: Supports Model-View-Controller design. The view processes the


information available in the model to generate the output.
Angular: Uses components and directives. Components are the directives
with a template.

63

You might also like