Angular Framework Overview and Setup
Angular Framework Overview and Setup
Angular - Introduction
Angular is a TypeScript based full-stack web framework for building web and mobile
applications. One of the major advantage is that the Angular support for web application
that can fit in any screen resolution. Angular application is fully compatible for mobiles,
tablets, laptops or desktops. Angular has an excellent user interface library for web
developers which contains reusable UI components.
This functionality helps us to create Single Page Applications (SPA). SPA is reactive and
fast application. For example, if you have a button in single page and click on the button
then the action performs dynamically in the current page without loading the new page
from the server. Angular is Typescript based object oriented programming and support
features for server side programming as well.
AngularJS
Angular 2.0
Angular 2.0 was released in September 2016. It is re-engineered and rewritten version
of AngularJS. AngularJs had a focus on controllers but, version 2 has changed focus on
Page 2 of 255
components. Components are the main building block of application. It supports features
for speed in rendering, updating pages and building cross-platform native mobile apps
for Google Android and iOS.
Angular 4.0
Angular 4.0 was released in March 2017. It is updated to TypeScript 2.2, supports ng if-
else conditions whereas Angular 2 supported only if conditions. Angular 4.0 introduces
animation packages, Http search parameters and finally angular 4 applications are
smaller and faster.
Angular 5.0
Angular 5.0 was released in November 2017. It supported some of the salient features
such as HTTPClient API, Lambda support, Improved Compiler and build optimizer.
Angular 6.0
Angular 6.0 was released in May 2018. Features added to this version are updated
Angular CLI, updated CDK, updated Angular Material, multiple validators and usage of
reactive JS library.
Angular 7.0
Angular 7.0 was released in October 2018. Some of salient features are Google
supported community, POJO based development, modular structure, declarative user
interface and modular structure.
Bazel support − If your application uses several modules and libraries, Bazel
concurrent builds helps to load faster in your application.
Lazy loading − Angular splits AppRoutingModule into smaller bundles and
loads the data in the DOM.
Opt-in usage sharing − User can opt into share Angular CLI usage data.
Applications
Some of the popular website using Angular Framework are listed below −
Angular - Installation
This chapter explains about how to install Angular on your machine. Before moving to
the installation, lets verify the prerequisite first.
Prerequisite
node --version
v14.2.0
If Node is not installed, you can download and install by visiting the following link −
[Link]
Angular installation
Page 4 of 255
Angular CLI installation is based on very simple steps. It will take not more than five
minutes to install.
npm is used to install Angular CLI. Once [Link] is installed, npm is also installed. If
you want verify it, type the below command
npm -v
6.14.4
To verify Angular is properly installed on your machine, type the below command −
ng version
Let us check whether the Angular Framework is installed in our system and the version
of the installed Angular version using below command −
ng --version
Here,
ng is the CLI application used to create, manage and run Angular Application. It written
in JavaScript and runs in NodeJS environment.
The result will show the details of the Angular version as specified below −
Let us create an Angular application to check our day to day expenses. Let us give
ExpenseManageras our choice for our new application. Use below command to create
the new application.
cd /path/to/workspace
ng new expense-manager
Here,
new is one of the command of the ng CLI application. It will be used to create new
application. It will ask some basic question in order to create new application. It is
enough to let the application choose the default choices. Regarding routing question as
mentioned below, specify No. We will see how to create routing later in the Routing
chapter.
Page 6 of 255
Once the basic questions are answered, the ng CLI application create a new Angular
application under expense-manager folder.
cd expense-manager
Let us check the partial structure of the application. The structure of the application is as
follows −
| [Link]
| [Link]
| [Link]
| [Link]
| [Link]
|
+---app
| [Link]
| [Link]
| [Link]
| [Link]
| [Link]
|
+---assets
| .gitkeep
|
+---environments
[Link]
[Link]
Here,
We have shown, only the most important file and folder of the application.
[Link] and assets are applications icon and applications root asset folder.
app folder contains the Angular application code, which will be learn elaborately
in the upcoming chapters.
ng serve
10% building 3/3 modules 0 activei wds: Project is running at [Link]
i wds: webpack output is served from /
Here, serve is the sub command used to compile and run the Angular application using
a local development web server. ng server will start a development web server and
serves the application under port, 4200.
Let us fire up a browser and opens [Link] The browser will show the
application as shown below −
Page 8 of 255
Let us change the title of the application to better reflect our application. Open
src/app/[Link] and change the code as specified below −
We will change the application and learn how to code an Angular application in the
upcoming chapters.
Angular - Architecture
Let us see the architecture of the Angular framework in this chapter.
Angular framework is based on four core concepts and they are as follows −
Components.
Modules.
Component
The core of the Angular framework architecture is Angular Component. Angular
Component is the building block of every Angular application. Every angular application
is made up of one more Angular Component. It is basically a plain JavaScript /
Typescript class along with a HTML template and an associated name.
Page 10 of 255
The HTML template can access the data from its corresponding JavaScript / Typescript
class. Components HTML template may include other component using its selectors value
(name). The Angular Component may have an optional CSS Styles associated it and the
HTML template may access the CSS Styles as well.
// src/app/[Link]
import { Component } from '@angular/core'; @Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
title = 'Expense Manager';
}
app-root is the selector / name of the component and it is specified using selector
meta data of the components decorator. app-root can be used by application root
document, src/[Link] as specified below
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ExpenseManager</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
Page 11 of 255
<body>
<app-root></app-root>
</body>
</html>
[Link] is the CSS style document associated with the component. The
component style is specified using styleUrls meta data of the @Component decorator.
AppComponent property (title) can be used in the HTML template as mentioned below
−
{{ title }}
Template
Template is basically a super set of HTML. Template includes all the features of HTML and
provides additional functionality to bind the component data into the HTML and to
dynamically generate HTML DOM elements.
The core concept of the template can be categorised into two items and they are as
follows −
Data binding
Used to bind the data from the component to the template.
{{ title }}
Directives
Used to include logic as well as enable creation of complex HTML DOM elements.
<p *ngIf="canShow">
This sectiom will be shown only when the *canShow* propery's value in the corr
Page 12 of 255
Here, ngIf and showToolTip (just an example) are directives. ngIf create the
paragraph DOM element only when canShow is true. Similarly, showToolTip is
Attribute Directives, which adds the tooltip functionality to the paragraph element.
When user mouse over the paragraph, a tooltip with be shown. The content of the tooltip
comes from tips property of its corresponding component.
Modules
Angular Module is basically a collection of related features / functionality. Angular
Module groups multiple components and services under a single context.
For example, animations related functionality can be grouped into single module and
Angular already provides a module for the animation related functionality,
BrowserAnimationModule module.
An Angular application can have any number of modules but only one module can be set
as root module, which will bootstrap the application and then call other modules as and
when necessary. A module can be configured to access functionality from other module
as well. In short, components from any modules can access component and services
from any other modules.
Following diagram depicts the interaction between modules and its components.
Page 13 of 255
Here,
Page 14 of 255
The following diagram depicts the relationship between Module, Component and Services
Services
Services are plain Typescript / JavaScript class providing a very specific functionality.
Services will do a single task and do it best. The main purpose of the service is
reusability. Instead of writing a functionality inside a component, separating it into a
service will make it useable in other component as well.
Also, Services enables the developer to organise the business logic of the application.
Basically, component uses services to do its own job. Dependency Injection is used to
properly initialise the service in the component so that the component can access the
services as and when necessary without any setup.
src/[Link] bootstraps the AppModule (src/[Link]), which is the root module for
every Angular application.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Page 16 of 255
Here,
AppModule also loads all the registered service using Dependency Injection (DI)
framework.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ExpenseManager</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-root></app-root>
</body>
</html>
@NgModule({
declarations: [
AppComponent
AnyOtherComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Component use other component through directive in its template using target
components selector name.
Page 17 of 255
<component-selector-name></component-selector-name>
Also, all registered services are accessible to all Angular components through
Dependency Injection (DI) framework.
Let us learn the basic concept of component and template in this chapter.
Add a component
Let us create a new component in our ExpenseManager application.
cd /go/to/expense-manager
Output
The output is mentioned below −
Here,
Here,
app-expense-entry is the selector value and it can be used as regular HTML Tag.
We will update the content of the component during the course of learning more about
templates.
Templates
The integral part of Angular component is Template. It is used to generate the HTML
content. Templates are plain HTML with additional functionality.
Attach a template
Template can be attached to Angular component using @component decorators meta
data. Angular provides two meta data to attach template to components.
templateUrl
We already know how to use templateUrl. It expects the relative path of the template
file. For example, AppComponent set its template as [Link].
templateUrl: './[Link]',
template
template enables to place the HTML string inside the component itself. If the template
content is minimal, then it will be easy to have it Component class itself for easy
tracking and maintenance purpose.
@Component({
selector: 'app-root',
templateUrl: `<h1>{{ title }}</h1>`,
styleUrls: ['./[Link]']
})
Page 20 of 255
Attach Stylesheet
Angular Templates can use CSS styles similar to HTML. Template gets its style
information from two sources, a) from its component b) from application configuration.
Component configuration
Component decorator provides two option, styles and styleUrls to provide CSS style
information to its template.
Styles − styles option is used to place the CSS inside the component itself.
Application configuration
Angular provides an option in project configuration ([Link]) to specify the CSS
stylesheets. The styles specified in [Link] will be applicable for all templates. Let
us check our [Link] as shown below −
{
"projects": {
"expense-manager": {
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser", "options": {
"outputPath": "dist/expense-manager",
Page 21 of 255
"index": "src/[Link]",
"main": "src/[Link]",
"polyfills": "src/[Link]",
"tsConfig": "[Link]",
"aot": false,
"assets": [
"src/[Link]",
"src/assets"
],
"styles": [
"src/[Link]"
],
"scripts": []
},
},
}
}},
"defaultProject": "expense-manager"
}
Here,
styles option setssrc/[Link] as global CSS stylesheet. We can include any number
of CSS stylesheets as it supports multiple values.
Include bootstrap
Let us include bootstrap into our ExpenseManager application using styles option and
change the default template to use bootstrap components.
cd /go/to/expense-manager
Here,
We have installed JQuery, because, bootstrap uses jquery extensively for advanced
components.
Page 22 of 255
{
"projects": {
"expense-manager": {
"architect": {
"build": {
"builder":"@angular-devkit/build-angular:browser", "options": {
"outputPath": "dist/expense-manager",
"index": "src/[Link]",
"main": "src/[Link]",
"polyfills": "src/[Link]",
"tsConfig": "[Link]",
"aot": false,
"assets": [
"src/[Link]",
"src/assets"
],
"styles": [
"./node_modules/bootstrap/dist/css/[Link]",
"src/[Link]"
],
"scripts": [
"./node_modules/jquery/dist/[Link]",
"./node_modules/bootstrap/dist/js/[Link]"
]
},
},
}
}},
"defaultProject": "expense-manager"
}
Here,
<div class="container">
<a class="navbar-brand" href="#">{{ title }}</a> <button class="navbar-
toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon">
</span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Report</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Add Expense</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</div>
</nav>
<app-expense-entry></app-expense-entry>
Here,
0px;">
<div class="row">
<div class="col-sm" style="text-align: left;"> {{ title }}
</div>
<div class="col-sm" style="text-align: right;">
<button type="button" class="btn btn-primary">Edit</button>
</div>
</div>
</div>
<div class="container box" style="margin-top: 10px;">
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Item:</em></strong>
</div>
<div class="col" style="text-align: left;">
Pizza
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Amount:</em></strong>
</div>
<div class="col" style="text-align: left;">
20
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Category:</em></strong>
</div>
<div class="col" style="text-align: left;">
Food
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Location:</em></strong>
</div>
<div class="col" style="text-align: left;">
Zomato
</div>
</div>
Page 25 of 255
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Spend On:</em></strong>
</div>
<div class="col" style="text-align: left;">
June 20, 2020
</div>
</div>
</div>
</div>
</div>
</div>
We will improve the application to handle dynamic expense entry in next chapter.
Open command prompt and create new Angular application using below command −
cd /go/to/workspace
ng new databind-app
cd databind-app
ng serve
String interpolation
Lets create a simple string property in component and bind the data to view.
<h1>{{appName}}</h1>
Add the test component in your [Link] file by replacing the existing
content as follows −
<app-test></app-test>
Finally, start your application (if not done already) using the below command −
ng serve
Event binding
Events are actions like mouse click, double click, hover or any keyboard and mouse
actions. If a user interacts with an application and performs some actions, then event
will be raised. It is denoted by either parenthesis () or on-. We have different ways to
bind an event to DOM element. Lets understand one by one in brief.
}
}
}
$event\ast\:refersthefiredevent\cdot\:Inthisscenario\:,\ast\:click
\ast\:istheevent\cdot\ast$event has all the information about event and the target
element. Here, the target is button. $[Link] property will have the target
information.
<h2>Event Binding</h2>
<button (click)="showData($event)">Click here</button>
Alternatively, you can use prefix - on using canonical form as shown below −
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 29 of 255
Here, when the user clicks on the button, event binding understands to button click
action and call component showData() method so we can conclude it is one-way binding.
Property binding
Property binding is used to bind the data from property of a component to DOM
elements. It is denoted by [].
Here,
Finally, start your application (if not done already) using the below command −
Page 30 of 255
ng serve
Attribute binding
Attribute binding is used to bind the data from component to HTML attributes. The
syntax is as follows −
For example,
Here,
Finally, start your application (if not done already) using the below command −
ng serve
Class binding
Class binding is used to bind the data from component to HTML class property. The
syntax is as follows −
Class Binding provides additional functionality. If the component data is boolean, then
the class will bind only when it is true. Multiple class can be provided by string (foo bar)
as well as Array of string. Many more options are available.
For example,
Page 32 of 255
<p [class]="myClasses">
.red {
color: red;
}
.blue {
color: blue;
}
Finally, start your application (if not done already) using the below command −
ng serve
Style binding
Style binding is used to bind the data from component into HTML style property. The
syntax is as follows −
For example,
myColor = 'brown';
Finally, start your application (if not done already) using the below command −
ng serve
Page 34 of 255
NgModel
For example,
Here,
Property is bind to form control ngModeldirective and if you enter any text in the
textbox, it will bind to the property. After running your application, you could see the
below changes −
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 36 of 255
Now, try to change the input value to Jack. As you type, the text below the input gets
changed and the final output will be as shown below −
Working example
Page 37 of 255
Let us implement all the concept learned in this chapter in our ExpenseManager
application.
cd /go/to/expense-manager
}
}
Angular - Directives
Angular directives are DOM elements to interact with your application. Generally,
directive is a TypeScript function. When this function executes Angular compiler
checked it inside DOM element. Angular directives begin with ng- where ng stands for
Angular and extends HTML tags with @directive decorator.
Directives enables logic to be included in the Angular templates. Angular directives can
be classified into three categories and they are as follows −
Attribute directives
Used to add new attributes for the existing HTML elements to change its look and
behaviour.
For example,
Here, showToolTip refers an example directive, which when used in a HTML element
will show tips while user hovers the HTML element.
Structural directives
For example,
<div *ngIf="isNeeded">
Only render if the *isNeeded* value has true value.
</div>
Here, ngIf is a built-in directive used to add or remove the HTML element in the current
HTML document. Angular provides many built-in directive and we will learn in later
chapters.
Component can be used as directives. Every component has Input and Output option to
pass between component and its parent HTML elements.
For example,
Here, list-item is a component and items is the input option. We will learn how to
create component and advanced usages in the later chapters.
Before moving to this topic, lets create a sample application (directive-app) in Angular
to work out the learnings.
Open command prompt and create new Angular application using below command −
cd /go/to/workspace
ng new directive-app
cd directive-app
ng serve
DOM Overview
Let us have a look at DOM model in brief. DOM is used to define a standard for accessing
documents. Generally, HTML DOM model is constructed as a tree of objects. It is a
standard object model to access html elements.
Page 42 of 255
Structural directives
Structural directives change the structure of DOM by adding or removing elements. It is
denoted by * sign with three pre-defined directives NgIf, NgFor and NgSwitch. Lets
understand one by one in brief.
NgIf directive
NgIf directive is used to display or hide data in your application based on the condition
becomes true or false. We can add this to any tag in your template.
<p>test works!</p>
<div *ngIf="true">Display data</div>
<app-test></app-test>
Start your server (if not started already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 43 of 255
ngIfElse directive
ngIfElse is similar to ngIf except, it provides option to render content during failure
scenario as well.
<p>ngIfElse example!</p>
<div *ngIf="isLogIn; else isLogOut">
Hello you are logged in
</div>
<ng-template #isLogOut>
You're logged out..
</ng-template>
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 44 of 255
Here,
isLogOut
value is assigned as true, so it goes to else block and renders ng-template. We will
learn ng-template later in this chapter.
ngFor directive
ngFor is used to repeat a portion of elements from the list of items.
list = [1,2,3,4,5];
<h2>ngFor directive</h2>
<ul>
<li *ngFor="let l of list">
{{l}}
</li>
</ul>
Here, the let keyword creates a local variable and it can be referenced anywhere in your
template. The let l creates a template local variable to get the list elements.
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 45 of 255
trackBy
Sometimes, ngFor performance is low with large lists. For example, when adding new
item or remove any item in the list may trigger several DOM manipulations. To iterate
over large objects collection, we use trackBy.
Lets understand how trackBy works along with ngFor by doing a sample.
}
];
trackByData(index:number, studentArr:any): number {
return [Link];
}
Here,
We have created,
trackByData()
method to access each student element in a unique way based on the id.
Add the below code in [Link] file to define trackBy method inside ngFor.
<ul>
<li *ngFor="let std of studentArr; trackBy: trackByData">
{{[Link]}}
</li>
</ul>
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Here, the application will print the student names. Now, the application is tracking
student objects using the student id instead of object references. So, DOM elements are
not affected.
NgSwitch directive
Page 47 of 255
NgSWitch is used to check multiple conditions and keep the DOM structure as simple
and easy to understand.
<h2>ngSwitch directive</h2>
<ul [ngSwitch]="logInName">
<li *ngSwitchCase="'user'">
<p>User is logged in..</p>
</li>
<li *ngSwitchCase="'admin'">
<p>admin is logged in</p>
</li>
<li *ngSwitchDefault>
<p>Please choose login name</p>
</li>
</ul>
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 48 of 255
Here, we have defined logInName as admin. So, it matches second SwitchCase and
prints above admin related message.
Attribute directives
Attribute directives performs the appearance or behavior of DOM elements or
components. Some of the examples are NgStyle, NgClass and NgModel. Whereas,
NgModel is two-way attribute data binding explained in previous chapter.
ngStyle
ngStyle directive is used to add dynamic styles. Below example is used to apply blue
color to the paragraph.
Start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 49 of 255
ngClass
ng g class User
Here, we have created two property userId and userName in the User class.
},
{
"userId": 2,
"userName": 'User2'
},
];
}
Here, we have declared a local variable, users and initialise with 2 users object.
.highlight {
color: red;
}
<div class="container">
<br/>
<div *ngFor="let user of users" [ngClass]="{
'highlight':[Link] === 'User1'
}">
{{ [Link] }}
</div>
</div>
Here,
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Page 51 of 255
Custom directives
Angular provides option to extend the angular directive with user defined directives and
it is called Custom directives. Let us learn how to create custom directive in this
chapter.
After executing this command, you could see the below response −
Here, constructor method gets the element using CustomStyleDirective as el. Then,
it accesses els style and set its font size as 24px using CSS property.
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
ng-template
ng-template is used to create dynamic and reusable templates. It is a virtual element.
If you compile your code with ng-template then is converted as comment in DOM.
For example,
<h3>ng-template</h3>
<ng-template>ng-template tag is a virtual element</ng-template>
If you run the application, then it will print only h3 element. Check your page source,
template is displayed in comment section because it is a virtual element so it does not
render anything. We need to use ng-template along with Angular directives.
Normally, directive emits the HTML tag it is associated. Sometimes, we dont want the tag
but only the content. For example, in the below example, li will be emitted.
<ng-template [ngIf]=true>
<div><h2>ng-template works!</h2></div>
</ng-template>
Here, if ngIf condition becomes true, it will print the data inside div element. Similarly,
you can use ngFor and ngSwitch directives as well.
NgForOf directive
ngForOf is also a structural directive used to render an item in a collection. Below
example is used to show ngForOf directive inside ng-template.
,
styleUrls: ['./[Link]']
})
export class TestComponent implements OnInit {
Fruits = ["mango","apple","orange","grapes"];
ngOnInit()
{
}
}
If you run the application, it will show the index of each elements as shown below −
0
1
2
3
Component directives
Component directives are based on component. Actually, each component can be used
as directive. Component provides @Input and @Output decorator to send and receive
information between parent and child components.
<p>child works!</p>
Page 55 of 255
<h1>Test component</h1>
<app-child [userName]="name"><app-child>
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
[](images/directive-app/component_as_directive.PNG"
Working example
Let us add a new component in our ExpenseManager application to list the expense
entries.
cd /go/to/expense-manager
ng serve
Output
Here, the command creates the ExpenseEntryList Component and update the necessary
code in AppModule.
getExpenseEntries() : ExpenseEntry[] {
let mockExpenseEntries : ExpenseEntry[] = [
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
category: "Food",
location: "Mcdonald",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
10, 10, 10) },
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
category: "Food",
location: "KFC",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
Page 57 of 255
Declare a local variable, expenseEntries and load the mock list of expense entries as
mentioned below −
title: string;
expenseEntries: ExpenseEntry[];
constructor() { }
ngOnInit() {
[Link] = "Expense Entry List";
Page 58 of 255
[Link] = [Link]();
}
</div>
</div>
</div>
</div>
Here,
Used bootstrap table. table and table-striped will style the table according to
Boostrap style standard.
Used ngFor to loop over the expenseEntries and generate table rows.
...
<app-expense-entry-list></app-expense-entry-list>
Angular - Pipes
Pipes are referred as filters. It helps to transform data and manage data within
interpolation, denoted by {{ | }}. It accepts data, arrays, integers and strings as inputs
which are separated by | symbol. This chapter explains about pipes in detail.
Page 60 of 255
Adding parameters
Create a date method in your [Link] file.
<div>
Today's date :- {{presentDate}}
</div>
Here,
<div>
Today's date :- {{presentDate | date }}
</div>
Parameters in Date
We can add parameter in pipe using : character. We can show short, full or formatted
dates using this parameter. Add the below code in [Link] file.
Page 61 of 255
<div>
short date :- {{presentDate | date:'shortDate' }} <br/>
Full date :- {{presentDate | date:'fullDate' }} <br/>
Formatted date:- {{presentDate | date:'M/dd/yyyy'}} <br/>
Hours and minutes:- {{presentDate | date:'h:mm'}}
</div>
Chained pipes
We can combine multiple pipes together. This will be useful when a scenario associates
with more than one pipe that has to be applied for data transformation.
In the above example, if you want to show the date with uppercase letters, then we can
apply both Date and Uppercase pipes together.
<div>
Date with uppercase :- {{presentDate | date:'fullDate' | uppercase}} <br/>
Date with lowercase :- {{presentDate | date:'medium' | lowercase}} <br/>
</div>
Date with uppercase :- MONDAY, JUNE 15, 2020 Date with lowercase :- jun 15, 2020,
Here,
Date, Uppercase and Lowercase are pre-defined pipes. Lets understand other types of
built-in pipes in next section.
Built-in Pipes
Angular supports the following built-in pipes. We will discuss one by one in brief.
Page 62 of 255
AsyncPipe
If data comes in the form of observables, then Async pipe subscribes to an observable
and returns the transmitted values.
Here,
The Async pipe performs subscription for time changing in every one seconds and
returns the result whenever gets passed to it. Main advantage is that, we dont need to
call subscribe on our timeChange and dont worry about unsubscribe, if the component is
removed.
<div>
Seconds changing in Time: {{ timeChange | async }}
</div>
Now, run the application, you could see the seconds changing on your screen.
CurrencyPipe
It is used to convert the given number into various countries currency format. Consider
the below code in [Link] file.
styleUrls: ['./[Link]']
})
export class TestComponent implements OnInit {
price : number = 20000; ngOnInit() {
}
}
Currency Pipe
20,000.00
20,000.00
SlicePipe
Slice pipe is used to return a slice of an array. It takes index as an argument. If you
assign only start index, means it will print till the end of values. If you want to print
specific range of values, then we can assign start and end index.
We can also use negative index to access elements. Simple example is shown below −
[Link]
}
}
Now run your application and you could see the below output on your screen −
Here,
{{Fruits | slice:2}} means it starts from second index value Grapes to till the
end of value.
{{Fruits | sli[Link]}} means starts from 1 to end-1 so the result is one to third
index values.
{{Fruits | slice:-2}} means starts from -2 to till end because no end value is
specified. Hence the result is Kiwi, Pomegranate.
DecimalPipe
It is used to format decimal values. It is also considered as CommonModule. Lets
understand a simple code in [Link] file,
ngOnInit() {
}
}
Decimal Pipe
8.759
5.43
Formatting values
We can apply string format inside number pattern. It is based on the below format −
number:"{minimumIntegerDigits}.{minimumFractionDigits} - {maximumFractionDigits}"
@Component({
template: `
<div style="text-align:center">
<p> Apply formatting:- {{decimalNum1 | number:'3.1'}} </p>
<p> Apply formatting:- {{decimalNum1 | number:'2.1-4'}} </p>
</div>
`,
})
Here,
{{decimalNum1 | number:2.1-4}} means two decimal places and minimum one and
maximum of four fractions allowed so it returns the below output −
PercentPipe
It is used to format number as percent. Formatting strings are same as DecimalPipe
concept. Simple example is shown below −
Decimal Pipe
81.78%
JsonPipe
It is used to transform a JavaScript object into a JSON string. Add the below code in
[Link] file as follows −
styleUrls: ['./[Link]']
})
export class TestComponent {
jsonData = { id: 'one', name: { username: 'user1' }}
}
Now, run the application, you could see the below output on your screen −
{{ jsonData }}
(1)
[object Object]
{{ jsonData | json }}
{ "id": "one", "name": { "username": "user1" } }
ng g pipe digitcount
After executing the above command, you could see the response −
Lets create a logic for counting digits in a number using Pipe. Open [Link]
file and add the below code −
}
}
Now, we have added logic for count number of digits in a number. Lets add the final code
in [Link] file as follows −
Now, run the application, you could see the below response −
DigitCount Pipe
3
Working example
Let us use the pipe in the our ExpenseManager application.
cd /go/to/expense-manager
ng serve
Page 69 of 255
Here, we have used the date pipe to show the spend on date in the short format.
Reactive programming enables the data stream to be emitted from one source called
Observable and the emitted data stream to be caught by other sources called
Observer through a process called subscription. This Observable / Observer pattern or
simple Observer pattern greatly simplifies complex change detection and necessary
updating in the context of the programming.
JavaScript does not have the built-in support for Reactive Programming. RxJs is a
JavaScript Library which enables reactive programming in JavaScript. Angular uses RxJs
library extensively to do below mentioned advanced concepts −
Page 70 of 255
HTTP client.
Router.
Reactive forms.
Observable
As learn earlier, Observable are data sources and they may be static or dynamic. Rxjs
provides lot of method to create Observable from common JavaScript Objects. Let us
see some of the common methods.
of − Emit any number of values in a sequence and finally emit a complete notification.
Here,
Dollar sign ($) at the end of the variable is to identify that the variable is
Observable.
ajax − Fetch a url through AJAX and then emit the response.
Here,
Page 71 of 255
[Link] is a free REST API service which will return the supplied body
content in the JSON format as specified below −
{
"args": {},
"data": "Hello",
"files": {},
"form": {},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Host": "[Link]", "Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
"X-Amzn-Trace-Id": "Root=1-5eeef468-015d8f0c228367109234953c"
},
"origin": "ip address",
"url": "[Link]
}
fromEvent − Listen to an HTML elements event and then emit the event and its
property whenever the listened event fires.
Angular internally uses the concept extensively to provide data transfer between
components and for reactive forms.
Subscribing process
Subscribing to an Observable is quite easy. Every Observable object will have a method,
subscribe for the subscription process. Observer need to implement three callback
function to subscribe to the Observable object. They are as follows −
next − Receive and process the value emitted from the Observable
complete − Callback function called when all data from Observable are emitted.
Page 72 of 255
Once the three callback functions are defined, Observables subscribe method has to be
called as specified below −
Here,
next − method get the emitted number and then push it into the local variable,
[Link].
We can skip error and complete method and write only the next method as shown
below −
Operations
Rxjs library provides some of the operators to process the data stream. Some of the
important operators are as follows −
map − Enables to map the data stream using callback function and to change the data
stream itself.
Page 73 of 255
const mapFn = map( (num : number) => num + num ); const mappedNumbers$ = mappedFn
Let us create a sample application to try out the reaction programming concept learned
in this chapter.
ng new reactive
cd reactive
ng serve
val1 : number = 0;
filteredNumbers : number[] = [];
val2 : number = 0;
processedNumbers : number[] = [];
val3 : number = 0;
apiMessage : string;
counter : number = 0;
ngOnInit() {
// Observable stream of data Observable<number>
// const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// const numbers$ = range(1,10);
const numbers$ = from([1,2,3,4,5,6,7,8,9,10]);
// observer
const observer = {
next: (num: number) => {[Link](num); this.val1 += num },
error: (err: any) => [Link](err),
complete: () => [Link]("Observation completed")
};
numbers$.subscribe(observer);
const filterFn = filter( (num : number) => num > 5 );
const filteredNumbers = filterFn(numbers$);
[Link]( (num : number) =>
{[Link](num); this.val2 += num } );
const mapFn = map( (num : number) => num + num );
const processedNumbers$ = numbers$.pipe(filterFn, mapFn);
processedNumbers$.subscribe( (num : number) =>
{[Link](num); this.val3 += num } );
const api$ = ajax({
url: '[Link]
method: 'POST',
headers: {'Content-Type': 'application/text' },
body: "Hello"
});
api$.subscribe(res => [Link] = [Link] );
const clickEvent$ = fromEvent([Link]('counter'),
'click');
clickEvent$.subscribe( () => [Link]++ );
}
}
Here,
Page 75 of 255
Used of, range, from, ajax and fromEvent methods to created Observable.
Used filter, map and pipe operator methods to process the data stream.
Callback functions catch the emitted data, process it and then store it in
components local variables.
Here,
Click the Click here link for five times. For each event, the event will be emitted and
forward to the Observer. Observer callback function will be called. The callback function
increment the counter for every click and the final result will be as shown below −
Also, Angular services may depend on another services to work properly. Dependency
resolution is one of the complex and time consuming activity in developing any
application. To reduce the complexity, Angular provides Dependency Injection pattern
as one of the core concept.
Let us learn, how to use Dependency Injection in Angular application in this chapter.
An Angular service is plain Typescript class having one or more methods (functionality)
along with @Injectable decorator. It enables the normal Typescript class to be used as
service in Angular application.
Here, @Injectable decorator converts a plain Typescript class into Angular service.
NullInjector
ModuleInjector @ root
The value should refer to the one of the registered Angular Module (decorated with
@NgModule). root is a special option which refers the root module of the application.
The sample code is as follows −
ModuleInjector @ platform
Page 78 of 255
Platform Injector is one level higher than ModuleInject and it is only in advanced and
rare situation. Every Angular application starts by executing
PreformBrowserDynamic().bootstrap method (see [Link]), which is responsible for
bootstrapping root module of Angular application.
NullInjector
NullInjector is one level higher than platform level ModuleInjector and is in the top
level of the hierarchy. We could not able to register any service in the NullInjector. It
resolves when the required service is not found anywhere in the hierarchy and simply
throws an error.
ExpenseEntryListComponent
// import statement
import { DebugService } from '../[Link]';
// component decorator
@Component({
selector: 'app-expense-entry-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
providers: [DebugService] })
ExpenseEntryListComponent
Page 79 of 255
// import statement
import { DebugService } from '../[Link]';
// component decorator
@Component({
selector: 'app-expense-entry-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]'], viewProviders: [DebugServic
})
Parent component can use a child component either through its view or content.
Example of a parent component with child and content view is mentioned below −
<div>
child template in view
<child></child>
</div>
<ng-content></ng-content>
<div>
child template in view
</div>
<parent>
<!-- child template in content -->
<child></child>
</parent>
Here,
child component is used in two place. One inside the parents view. Another
inside parent content.
Services will be available in child component, which is placed inside parents view.
Page 80 of 255
Services will not be available in child component, which is placed inside parents
content.
Here,
First, component tries to find the service registered using viewProviders meta
data.
If not found, component tries to find the service registered using providers meta
data.
If not found, component tries to find the service registered using NullInjector,
which always throws error.
The hierarchy of the Injector along with work flow of the resolving the service is as
follows −
Page 83 of 255
Resolution Modifier
As we learn in the previous chapter, the resolution of the service starts from component
and stops either when a service is found or NUllInjector is reached. This is the default
resolution and it can be changed using Resolution Modifier. They are as follows −
Self()
Self() start and stops the search for the service in its current ElementInjector itself.
SkipSelf()
SkipSelf() is just opposite to Self(). It skips the current ElementInjector and starts the
search for service from its parent ElementInjector.
Host()
Host() stop the search for the service in its host ElementInjector. Even if service
available up in the higher level, it stops at host.
Page 84 of 255
Optional()
Optional() does not throws the error when the search for the service fails.
providers: [ DebugService ]
Here, DebugService is both token as well as the class, with which the service object
has to be created. The actual form of the provider is as follows −
Here, provides is the token and useClass is the class reference to create the service
object.
providers: [ DebugService,
{ provides: AnotherDebugService, userClass: DebugService }]
Page 85 of 255
Value providers
The purpose of the Value providers is to supply the value itself instead of asking the DI
to create an instance of the service object. It may use existing object as well. The only
restriction is that the object should be in the shape of referenced service.
Here, DI provider just return the instance set in useValue option instead of creating a
new service object.
Factory providers
Factory Providers enables complex service creation. It delegates the creation of the
object to an external function. Factory providers has option to set the dependency for
factory object as well.
Here,
Angular Dependency Injector (DI) will try to find any service registered in the
application with type DebugService. If found, it will set an instance of
DebugService to ExpenseEntryListComponent component. If not found, it will
throw an error.
cd /go/to/expense-manager
ng serve
ng g service debug
Page 87 of 255
This will create two Typescript files (debug service & its test) as specified below −
Here,
providerIn option and its value, root enables the DebugService to be used in all
component of the application.
Let us add a method, Info, which will print the message into the browser console.
component initialized");
[Link] = "Expense Entry List";
[Link] = [Link]();
}
// other coding
}
Here,
Calling the info method of DebugService in the ngOnInit method prints the
message in the browser console.
The
result can be viewed using developer tools and it looks similar as shown below −
// src/app/[Link]
import { Injectable } from '@angular/core'; @Injectable()
export class DebugService {
constructor() {
}
info(message : String) : void {
[Link](message);
}
}
// src/app/expense-entry-list/[Link] @Component({
selector: 'app-expense-entry-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
providers: [DebugService]
})
Here, we have used providers meta data (ElementInjector) to register the service.
Here, we have not registered DebugService. So, DebugService will not be available if
used as parent component. When used inside a parent component, the service may
available from parent, if the parent has access to the service.
// existing content
<app-debug></app-debug>
<ng-content></ng-content>
// navigation code
<app-expense-entry-list>
<app-debug></app-debug>
</app-expense-entry-list>
Let us check the application and it will show DebugService template at the end of the
page as shown below −
Page 91 of 255
Also, we could able to see two debug information from debug component in the console.
This indicate that the debug component gets the service from its parent component.
Let us change how the service is injected in the ExpenseEntryListComponent and how
it affects the scope of the service. Change providers injector to viewProviders injection.
viewProviders does not inject the service into the content child and so, it should fail.
viewProviders: [DebugService]
Check the application and you will see that the one of the debug component (used as
content child) throws error as shown below −
Page 92 of 255
Let us remove the debug component in the templates and restore the application.
<app-debug></app-debug>
<ng-content></ng-content>
// navigation code
<app-expense-entry-list>
</app-expense-entry-list>
providers: [DebugService]
Let us learn how to how to use HttpClient service in this chapter. Developer should have
a basic knowledge in Http programming to understand this chapter.
Let us create an Expense Rest API using express framework and then access it from
our ExpenseManager application using Angular HttpClient service.
cd /go/to/workspace
mkdir express-rest-api
cd expense-rest-api
npm init
npm init will ask some basic questions like project name (express-rest-api), entry point
([Link]), etc., as mentioned below −
[Link] = db
Here, we are creating a new sqlite database and load some sample data.
[Link]({"message":"Ok"})
});
});
amount = ?,
category = ?,
location = ?,
spendOn = ?
WHERE id = ?`,
[[Link], [Link], [Link],
[Link],[Link], [Link]],
function (err, result) {
if (err){
[Link](err);
[Link](400).json({"error": [Link]})
return;
}
[Link](data)
});
})
Page 98 of 255
[Link](function(req, res){
[Link](404);
});
Here, we create a basic CURD rest api to select, insert, update and delete expense entry.
Open a browser, enter [Link] and press enter. You will see below
response −
{
"message": "Ok"
}
Change the url to [Link] and you will see all the
expense entries in JSON format.
[
{
"id": 1,
"item": "Pizza",
"amount": 10,
Page 99 of 255
"category": "Food",
"location": "KFC",
"spendOn": "2020-05-26 10:10",
"createdOn": "2020-05-26 10:10"
},
{
"id": 2,
"item": "Pizza",
"amount": 14,
"category": "Food",
"location": "Mcdonald",
"spendOn": "2020-06-01 18:14",
"createdOn": "2020-05-01 18:14"
},
{
"id": 3,
"item": "Pizza",
"amount": 15,
"category": "Food",
"location": "KFC",
"spendOn": "2020-06-06 16:18",
"createdOn": "2020-06-06 16:18"
},
{
"id": 4,
"item": "Pizza",
"amount": 9,
"category": "Food",
"location": "Mcdonald",
"spendOn": "2020-05-28 11:10",
"createdOn": "2020-05-28 11:10"
},
{
"id": 5,
"item": "Pizza",
"amount": 12,
"category": "Food",
"location": "Mcdonald",
"spendOn": "2020-05-29 09:22",
"createdOn": "2020-05-29 09:22"
}
]
Page 100 of 255
Finally, we created a simple CURD REST API for expense entry and we can access the
REST API from our Angular application to learn HttpClient module.
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
]
})
export class AppModule {}
cd /go/to/expense-manager
ng serve
Page 101 of 255
This will create two Typescript files (expense entry service & its test) as specified below
−
Create a variable, httpOptions to set the Http Header option. This will be used during
the Http Rest API call by Angular HttpClient service.
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class ExpenseEntryService {
private expenseRestUrl = 'api/expense';
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
constructor(
private httpClient : HttpClient) { }
}
HTTP GET
HttpClient provides get() method to fetch data from a web page. The main argument is
the target web url. Another optional argument is the option object with below format −
{
headers?: HttpHeaders | {[header: string]: string | string[]},
observe?: 'body' | 'events' | 'response',
Here,
headers − HTTP Headers of the request, either as string, array of string or array
of HttpHeaders.
observe − Process the response and return the specific content of the response.
Possible values are body, response and events. The default option of observer is
Page 103 of 255
body.
get() method returns the response of the request as Observable. The returned
Observable emit the data when the response is received from the server.
[Link](url, options)
.subscribe( (data) => [Link](data) );
Typed Response
get() method has an option to return observables, which emits typed response as well.
The sample code to get typed response (ExpenseEntry) is as follows:
Handling errors
Error handling is one of the important aspect in the HTTP programming. Encountering
error is one of the common scenario in HTTP programming.
Client side issues can occur due to network failure, misconfiguration, etc., If client
side error happens, then the get() method throws ErrorEvent object.
Server side issues can occur due to wrong url, server unavailability, server
programming errors, etc.,
[Link](url, options)
.pipe(catchError([Link])
.subscribe( (data) => [Link](data) )
We can use rxjs librarys retry operator in this scenario as specified below
[Link](url, options)
.pipe(
retry(5),
catchError([Link]))
.subscribe( (data) => [Link](data) )
Let us do the actual coding to fetch the expenses from Expense Rest API in our
ExpenseManager application.
cd /go/to/expense-manager
Page 105 of 255
ng serve
getExpenseEntries() : Observable<ExpenseEntry[]> {
return [Link]<ExpenseEntry[]>([Link],
[Link])
.pipe(retry(3),catchError([Link]));
}
Here,
getExpenseEntries() calls the get() method using expense end point and also
configures the error handler. Also, it configures httpClient to try for maximum of
3 times in case of failure. Finally, it returns the response from server as typed
(ExpenseEntry[]) Observable object.
Page 106 of 255
@Injectable({
providedIn: 'root'
})
export class ExpenseEntryService {
private expenseRestUrl = '[Link]
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
getExpenseEntries() : Observable {
return [Link]([Link], [Link])
.pipe(
retry(3),
catchError([Link])
);
}
getExpenseItems() {
[Link]()
.subscribe( data =− [Link] = data );
}
@Component({
selector: 'app-expense-entry-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
providers: [DebugService]
})
Page 108 of 255
ngOnInit() {
[Link]("Expense Entry List component initialized");
[Link] = "Expense Entry List";
[Link]();
}
getExpenseItems() {
[Link]()
.subscribe( data => [Link] = data );
}
}
Finally, check the application and you will see the below response.
HTTP POST
HTTP POST is similar to HTTP GET except that the post request will send the necessary
data as posted content along with the request. HTTP POST is used to insert new record
into the system.
Page 109 of 255
HttpClient provides post() method, which is similar to get() except it support extra
argument to send the data to the server.
HTTP PUT
HTTP PUT is similar to HTTP POST request. HTTP PUT is used to update existing record in
the system.
HTTP DELETE
HTTP DELETE is similar to http GET request. HTTP DELETE is used to delete entries in the
system.
cd /go/to/expense-manager
ng add @angular/material
Angular CLI will ask certain question regarding theme, gesture recognition and browser
animations. Select your any theme of your choice and then answer positively for gesture
recognition and browser animation.
Angular material packages each UI component in a separate module. Import all the
necessary
module into the application through root module (src/app/[Link])
@NgModule({
imports: [
MatTableModule,
MatButtonModule,
MatIconModule
]
})
ng serve
Working example
Form field
Input
Checkbox
Radio button
Select
Button
DatePicker
List
Card
Grid list
Table
Paginator
Tabs
Toolbar
Menu
Dialog
Snackbar
Page 113 of 255
Progress bar
Icon
Divider
Using material component is quite easy and we will learn one of the frequently used
material component, Material Table by working on a sample project.
ng add @angular/material
<div class="mat-elevation-z8">
<table mat-table [dataSource]="expenseEntries">
<ng-container matColumnDef="item">
<th mat-header-cell *matHeaderCellDef> Item </th>
<td mat-cell *matCellDef="let element" style="text-align: left">
{{[Link]}} </td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef > Amount </th>
<td mat-cell *matCellDef="let element" style="text-align: left">
{{[Link]}} </td>
</ng-container>
<ng-container matColumnDef="category">
<th mat-header-cell *matHeaderCellDef> Category </th>
<td mat-cell *matCellDef="let element" style="text-align: left">
{{[Link]}} </td>
</ng-container>
Page 114 of 255
<ng-container matColumnDef="location">
<th mat-header-cell *matHeaderCellDef> Location </th>
<td mat-cell *matCellDef="let element" style="text-align:left">
{{[Link]}} </td>
</ng-container>
<ng-container matColumnDef="spendOn">
<th mat-header-cell *matHeaderCellDef> Spend On </th>
<td mat-cell *matCellDef="let element" style="text-align: left">
{{[Link]}} </td>
</ng-container>
Here,
Material table is template based and each column can be designed using separate
template. ng-container is used to create template.
matColumnDef is used to specify the column of the data source applied to the
particular ng-container.
We have used only the basic features of the Material table. Material table has
many more features such as sorting, pagination, etc.
ng serve
Configure Routing
Angular CLI provides complete support to setup routing during the application creation
process as well as during working an application. Let us create a new application with
router enabled using below command −
Angular CLI generate a new module, AppRoutingModuele for routing purpose. The
generated code is as follows −
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here,
Routes is the local variable (of type Routes) used to configure the actual
navigation rules of the application.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
Page 117 of 255
})
export class AppModule { }
Here,
Angular CLI provides option to set routing in the existing application as well. The general
command to include routing in an existing application is as follows −
This will generate new module with routing features enabled. To enable routing feature in
the existing module (AppModule), we need to include extra option as specified below −
Here,
module app configures the newly created routing module, AppRoutingModule in the
AppModule module.
cd /go/to/expense-manager
Output
Here,
Creating routes
Creating a route is simple and easy. The basic information to create a route is given
below −
Here,
Accessing routes
Let us learn how to use the configured routes in the application.
<router-outlet></router-outlet>
Here,
routerLinkActive set the CSS class to be used when the route is activated.
Page 119 of 255
Sometime, we need to access routing inside the component instead of template. Then,
we need to follow below steps −
Here,
[Link](['about']);
Here,
Route path is similar to web page URL and it supports relative path as well. To access
AboutComponent from another component, say HomePageComponent, simple use ..
notation as in web url or folder path.
Here,
Route ordering
Page 120 of 255
Redirect routes
Angular route allows a path to get redirected to another path. redirectTo is the option
to set redirection path. The sample route is as follows −
Here,
redirectTo sets about as the redirection path if the actual path matches empty
string.
Wildcard routes
Wildcard route will match any path. It is created using ** and will be used to handle non
existing path in the application. Placing the wildcard route at the end of the configuration
make it called when other path is not matched.
Here,
If a non existent page is called, then the first two route gets failed. But, the final
wildcard route will succeed and the PageNotFoundComponent gets called.
Using Observable.
Using snapshot (non-observable option).
Using Observable
Angular provides a special interface, paramMap to access the parameter of the path.
parmaMap has following methods −
get(name) − Returns the value of the specified name in the path (parameter
list).
getAll(name) − Returns the multiple value of the specified name in the path.
get() method returns only the first value when multiple values are available.
ngOnInit() {
[Link](params => {
[Link] = [Link]('id);
Page 122 of 255
});
}
[Link]$ = [Link](
switchMap(params => {
[Link] = Number([Link]('id'));
return [Link]([Link]);
})
);
Using snapshot
snapshot is similar to Observable except, it does not support observable and get the
parameter value immediately.
let id = [Link]('id');
Nested routing
In general, router-outlet will be placed in root component (AppComponent) of the
application. But, router-outlet can be used in any component. When router-outlet is used
in a component other then root component, the routes for the particular component has
to be configured as the children of the parent component. This is called Nested routing.
<h2>Item Component</h2>
<nav>
<ul>
<li><a routerLink="view">View</a></li>
<li><a routerLink="edit">Edit</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
The route for the ItemComponent has to be configured as Nested routing as specified
below −
Page 123 of 255
component: ItemComponent,
children: [
{
path: 'view',
component: ItemViewComponent
},
{
path: 'edit',
component: ItemEditComponent
}
]
}]
Working example
Let us apply the routing concept learned in this chapter in our ExpenseManager
application.
cd /go/to/expense-manager
Output
Here,
Here, we have added route for our expense list and expense details component.
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</div>
</nav>
<router-outlet></router-outlet>
Here, we have updated the expense list table and added a new column to show the view
option.
It can be done by first getting the id through the paramMap and then, using the
getExpenseEntry() method from ExpenseEntryService.
[Link]$ = [Link](
switchMap(params => {
[Link] = Number([Link]('id'));
return
[Link]([Link]); }));
[Link]$.subscribe( (data) => [Link] = data );
goToList() {
[Link](['/expenses']);
}
[Link] = Number([Link]('id'));
return
[Link]([Link]); }));
[Link]$.subscribe( (data) => [Link] = data );
}
goToList() {
[Link](['/expenses']);
}
}
ng serve
Clicking the view option of the first entry will navigate to details page and show the
selected expense entry as shown below −
Angular - Animations
Animation gives the web application a refreshing look and rich user interaction. In HTML,
animation is basically the transformation of HTML element from one CSS style to another
over a specific period of time. For example, an image element can be enlarged by
changing its width and height.
If the width and height of the image is changed from initial value to final value in steps
over a period of time, say 10 seconds, then we get an animation effect. So, the scope of
Page 129 of 255
the animation depends on the feature / property provided by the CSS to style a HTML
element.
@Component({
animations: [
// animation functionality goes here
]
})
export class MyAnimationComponent
Concepts
Page 130 of 255
In angular, we need to understand the five core concept and its relationship to do
animation.
State
State refers the specific state of the component. A component can have multiple defined
state. The state is created using state() method. state() method has two arguments.
animations: [
...
state('start', style( { width: 200px; } ))
...
]
Style
Style refers the CSS style applied in a particular state. style() method is used to style
the particular state of a component. It uses the CSS property and can have multiple
items.
animations: [
...
state('start', style( { width: 200px; opacity: 1 } ))
...
]
Here, start state defines two CSS property, width with value 200px and opacity with
value 1.
Transition
Transition refers the transition from one state to another. Animation can have multiple
transition. Each transition is defined using transition() function. transition() takes two
argument.
Specifies the direction between two transition state. For example, start => end
refers that the initial state is start and the final state is end. Actually, it is an
Page 131 of 255
animations: [
...
transition('start => end', [
animate('1s')
])
...
]
Here, transition() function defines the transition from start state to end state with
animation defined in animate() method.
Animation
Animation defines the way the transition from one state to another take place.
animation() function is used to set the animation details. animate() takes a single
argument in the form of below expression −
delay − refers the delay time to start the transition. It is expressed similar to
duration
Trigger
Every animation needs a trigger to start the animation. trigger() method is used to set
all the animation information such as state, style, transition and animation in one place
and give it a unique name. The unique name is used further to trigger the animation.
animations: [
trigger('enlarge', [
state('start', style({
height: '200px',
Page 132 of 255
})),
state('end', style({
height: '500px',
})),
transition('start => end', [
animate('1s')
]),
transition('end => start', [
animate('0.5s')
]) ]),
]
Here, enlarge is the unique name given to the particular animation. It has two state and
related styles. It has two transition one from start to end and another from end to start.
End to start state do the reverse of the animation.
<div [@triggerName]="expression">...</div>;
For example,
Here,
If isEnlarge value is changed to true, then end state will be set and it triggers
start => end transition.
If isEnlarge value is changed to false, then start state will be set and it triggers
end => start transition.
Let us write a new angular application to better understand the animation concept by
enlarging an image with animation effect.
cd /go/to/workspace
ng new animation-app
Page 133 of 255
cd animation-app
Add animation functionality, which will animate the image during the enlarging /
shrinking of the image.
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
animations: [
trigger('enlarge', [
state('start', style({
height: '150px'
})),
state('end', style({
height: '250px'
Page 134 of 255
})),
transition('start => end', [
animate('1s 2s')
]),
transition('end => start', [
animate('1s 2s')
])
])
]
})
Attach the animation in the image tag. Also, attach the click event for the button.
<br />
<button (click)='triggerAnimation()'>{{ [Link] }}</button>
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
animations: [
trigger('enlarge', [
state('start', style({
height: '150px'
})),
state('end', style({
height: '250px'
})),
transition('start => end', [
animate('1s 2s')
]),
transition('end => start', [
animate('1s 2s')
])
])
]
})
export class AppComponent {
title = 'Animation Application';
isEnlarge: boolean = false;
buttonText: string = "Enlarge";
triggerAnimation() {
[Link] = ![Link];
if([Link])
[Link] = "Shrink";
else
Page 136 of 255
[Link] = "Enlarge";
}
}
ng serve
Click the enlarge button, it will enlarge the image with animation. The result will be as
shown below −
Click the button again to shrink it. The result will be as shown below −
Page 137 of 255
Angular - Forms
Forms are used to handle user input data. Angular supports two types of forms. They are
Template driven forms and Reactive forms. This section explains about Angular
forms in detail.
Configure Forms
imports: [
BrowserModule,
AppRoutingModule,
FormsModule //Assign FormsModule
],
Once, FormsModule is imported, the application will be ready for form programming.
Open command prompt and create new Angular application using below command −
cd /go/to/workspace
ng new template-form-app
cd template-form-app
...
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Page 139 of 255
@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
ngOnInit() {
}
onClickSubmit(result) {
[Link]("You have entered : " + [Link]);
Page 140 of 255
}
}
<app-test></app-test>
Finally, start your application (if not done already) using the below command −
ng serve
Now, run your application and you could see the below response −
Enter Peter in input text field and enter submit. onClickSubmit function will be called
and user entered text Peter will be send as an argument. onClickSubmit will print the
user name in the console and the output is as follows −
Page 141 of 255
Reactive Forms
Reactive Forms is created inside component class so it is also referred as model driven
forms. Every form control will have an object in the component and this provides greater
control and flexibility in the form programming. Reactive Form is based on structured
data model. Lets understand how to use Reactive forms in angular.
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
Page 142 of 255
Before moving to create Reactive forms, we need to understand about the following
concepts,
Open command prompt and create new Angular application using below command −
cd /go/to/workspace
ng new reactive-form-app
cd reactive-form-app
...
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
Page 143 of 255
})
export class AppModule { }
@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class TestComponent implements OnInit {
userName;
formdata;
ngOnInit() {
[Link] = new FormGroup({
userName: new FormControl("Tutorialspoint")
});
}
Page 144 of 255
Here,
<div>
<form [formGroup]="formdata" (ngSubmit)="onClickSubmit([Link])" >
<input type= text" name="userName" placeholder="userName"
formControlName = "userName">
<br/>
<br/>
<input type="submit" value="Click here">
</form>
</div>
<p> Textbox result is: {{userName}} </p>
Here,
ngSubmit event property is used in the form and set onClickSubmit() method as
its value.
<app-test></app-test>
Finally, start your application (if not done already) using the below command −
ng serve
Page 145 of 255
Now, run your application and you could see the below response −
Enter Tutorialspoint in input text field and enter submit. onClickSubmit function will
be called and user entered text Peter will be send as an argument.
RequiredValidator
Lets perform simple required field validation in angular.
cd /go/to/reactive-form-app
@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
}
}
Here,
We have used form builder to handle all the validation. Constructor is used to create a
form with the validation rules.
<div>
<h2>
Required Field validation
</h2>
<form [formGroup]="requiredForm" novalidate>
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div *ngIf="[Link]['name'].invalid &&
[Link]['name'].touched" class="alert alert-danger">
<div *ngIf="[Link]['name'].[Link]">
Name is required.
</div>
</div>
</form>
<p>Form value: {{ [Link] | json }}</p>
<p>Form status: {{ [Link] | json }}</p>
</div>
Here,
Conditional statement is used to check, if a user has touched the input field but
not enter the values then, it displays the error message.
Finally, start your application (if not done already) using the below command −
ng serve
Now run your application and put focus on text box. Then, it will use show Name is
required as shown below −
Page 148 of 255
If you enter text in the textbox, then it is validated and the output is shown below −
PatternValidator
PatternValidator is used to validate regex pattern. Lets perform simple email
validation.
cd /go/to/reactive-form-app
@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
myForm() {
[Link] = [Link]({
email: ['', [[Link],
[Link]("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")] ]
});
}
ngOnInit()
{
}
}
Here,
<div>
<h2>
Pattern validation
</h2>
<form [formGroup]="requiredForm" novalidate>
<div class="form-group">
Page 150 of 255
<label class="center-block">Email:
<input class="form-control" formControlName="email">
</label>
</div>
<div *ngIf="[Link]['email'].invalid &&
[Link]['email'].touched" class="alert alert-danger">
<div *ngIf="[Link]['email'].[Link]">
Email is required.
</div>
</div>
</form>
<p>Form value: {{ [Link] | json }}</p>
<p>Form status: {{ [Link] | json }}</p>
</div>
Here, we have created the email control and called email validator.
Run your application and you could see the below result −
Page 151 of 255
Authorization is the process of giving permission to the user to access certain resource
in the system. Only the authenticated user can be authorised to access a resource.
Guards in Routing
In a web application, a resource is referred by url. Every user in the system will be
allowed access a set of urls. For example, an administrator may be assigned all the url
coming under administration section.
As we know already, URLs are handled by Routing. Angular routing enables the urls to
be guarded and restricted based on programming logic. So, a url may be denied for a
normal user and allowed for an administrator.
Angular provides a concept called Router Guards which can be used to prevent
unauthorised access to certain part of the application through routing. Angular provides
multiple guards and they are as follows:
CanDeactivate − Used to stop ongoing process getting feedback from user. For
example, delete process can be stop if the user replies in negative.
Working example
Let us try to add login functionality to our application and secure it using CanActivate
guard.
cd /go/to/expense-manager
ng serve
@Injectable({
providedIn: 'root'
})
export class AuthService {
return of([Link]).pipe(
delay(1000),
tap(val => {
[Link]("Is User Authentication is successful: " + val);
})
);
}
logout(): void {
[Link] = false;
[Link]('isUserLoggedIn');
}
constructor() { }
}
Here,
Authentication validation is that the user name and password should be admin.
We have not used any backend. Instead, we have simulated a delay of 1s using
Observables.
The purpose of the logout method is to invalidate the user and removes the
information stored in localStorage.
@Component({
selector: 'app-login',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class LoginComponent implements OnInit {
userName: string;
password: string;
formData: FormGroup;
ngOnInit() {
[Link] = new FormGroup({
userName: new FormControl("admin"),
password: new FormControl("admin"),
});
}
onClickSubmit(data: any) {
[Link] = [Link];
[Link] = [Link];
[Link]([Link], [Link])
.subscribe( data => {
[Link]("Is Login Success: " + data);
Page 155 of 255
if(data) [Link](['/expenses']);
});
}
}
Here,
placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-
block" type="submit">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Here,
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
input {
margin-bottom: 20px;
}
@Component({
selector: 'app-logout',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class LogoutComponent implements OnInit {
ngOnInit() {
[Link]();
[Link](['/']);
}
Here,
@Injectable({
providedIn: 'root'
})
export class ExpenseGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree {
let url: string = [Link];
return [Link](url);
}
Here,
checkLogin will check whether the localStorage has the user information and if it
is available, then it returns true.
If the user is logged in and goes to login page, it will redirect the user to
expenses page
If the user is not logged in, then the user will be redirected to login page.
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here,
Created two new routes, login and logout to access LoginComponent and
LogoutComponent respectively.
Open AppComponent template and add two login and logout link.
</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/expenses">Report</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Add Expense</a>
</li>
<li class="nav-item">
<ng-template #isLogOut>
<a class="nav-link"
routerLink="/login">Login</a>
</ng-template>
</li>
</ul>
</div>
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
Page 161 of 255
ngOnInit() {
let storeData = [Link]("isUserLoggedIn");
[Link]("StoreData: " + storeData);
[Link] = false;
}
}
Here, we have added the logic to identify the user status so that we can show login /
logout functionality.
Now, run the application and the application opens the login page.
Page 162 of 255
Enter admin and admin as username and password and then, click submit. The
application process the login and redirects the user to expense list page as shown below
−
Web workers enables JavaScript application to run the CPU-intensive in the background
so that the application main thread concentrate on the smooth operation of UI. Angular
provides support for including Web workers in the application. Let us write a simple
Angular application and try to use web workers.
cd /go/to/workspace
ng new web-worker-sample
cd web-worker-sample
npm run start
Here,
// [Link]
{
"extends": "./[Link]",
"compilerOptions": {
Page 164 of 255
"outDir": "./out-tsc/worker",
"lib": [
"es2018",
"webworker"
],
"types": []
},
"include": [
"src/**/*.[Link]"
]
}
Here,
Here,
Basically, it excludes all the worker from compiling as it has separate configuration.
Here,
// src/app/[Link]
addEventListener('message', ({ data }) => {
const response = `worker response to ${data}`;
postMessage(response);
});
Page 165 of 255
Here,
A web worker is created. Web worker is basically a function, which will be called when a
message event is fired. The web worker will receive the data send by the caller, process
it and then send the response back to the caller.
Here,
Restart the application. Since the [Link] file is changed, which is not watched by
Angular runner, it is necessary to restart the application. Otherwise, Angular does not
identify the new web worker and does not compile it.
return true;
}
idx++;
[Link](idx);
}
return idx - 1;
}
}
Here,
Import the new created prime number class into src/app/[Link] and change the
logic of the web worker to find nth prime number.
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
title = 'Web worker sample';
prime10 : number = 0;
prime10000 : number = 0;
find10thPrimeNumber() {
this.prime10 = [Link](10);
}
find10000thPrimeNumber() {
if (typeof Worker !== 'undefined') {
// Create a new
const worker = new Worker('./[Link]', { type: 'module' });
[Link] = ({ data }) => {
this.prime10000 = data;
};
[Link](10000);
} else {
// Web Workers are not supported in this environment.
// You should add a fallback so that your program still executes
correctly.
}
}
}
Here,
<div>
<a href="#" (click)="find10thPrimeNumber()">Click here</a> to find 10th
prime number
<div>The 10<sup>th</sup> prime number is {{ prime10 }}</div> <br/>
<a href="#" (click)="find10000thPrimeNumber()">Click here</a> to find
10000th prime number
<div>The 10000<sup>th</sup> prime number is {{ prime10000 }}</div>
</div>
Here,
Finding 10000th prime number will take few seconds, but it will not affect other process
as it is uses web workers. Just try to find the 10000th prime number first and then, the
10th prime number.
Since, the web worker is calculating 10000th prime number, the UI does not freeze. We
can check 10th prime number in the meantime. If we have not used web worker, we
could not do anything in the browser as it is actively processing the 10000th prime
number.
Click and try to find the 10000th prime number and then try to find the 10th prime
number. The application finds the 10th prime number quite fast and shows it. The
application is still processing in the background to find the 10000th prime number.
Page 169 of 255
Web worker enhances the user experience of web application by doing the complex
operation in the background and it is quite easy to do it in Angular Application as well.
PWA can be installed in the system like native application and shortcut can be shown in
the desktop. Clicking the shortcut will open the application in browser with local cache
even without any network available in the system.
Service workers is separate from web pages. It does not able to access DOM objects.
Instead, Service Workers interact with web pages through PostMessage interface.
Browser support − Even though lot of browser supports the PWA app, IE,
Opera mini and few other does not provides the PWA support.
cd /go/to/workspace
ng new pwa-sample
cd pwa-sample
ng add @angular/pwa --project pwa-sample
ng build --prod
PWA application does not run under Angular development server. Install, a simple web
server using below command −
Run the web server and set our production build of the application as root folder.
Page 171 of 255
But in SSR supported application, the server as well do all the necessary configuration
and then send the final response to the browser. The browser renders the response and
start the SPA app. SPA app takeover from there and further request are diverted to SPA
app. The flow of SPA and SSR is as shown in below diagram.
Page 172 of 255
Converting a SPA application to SSR provides certain advantages and they are as follows
−
Speed − First request is relatively fast. One of the main drawback of SPA is slow
initial rendering. Once the application is rendered, SPA app is quite fast. SSR
fixes the initial rendering issue.
SEO Friendly − Enables the site to be SEO friendly. Another main disadvantage
of SPA is not able to crawled by web crawler for the purpose of SEO. SSR fixes
the issue.
Angular Universal
To enable SSR in Angular, Angular should be able to rendered in the server. To make it
happen, Angular provides a special technology called Angular Universal. It is quite new
Page 173 of 255
Let us learn how to create a simple hello world application in different language.
cd /go/to/workspace
ng new i18n-sample
cd i18n-sample
npm run start
<div>Hello</div>
<div>The Current time is {{ currentDate | date : 'medium' }}</div>
ng add @angular/localize
LOCALE_ID is the Angular variable to refer the current locale. By default, it is set as
en_US. Let us change the locale by using in the provider in AppModule.
Page 174 of 255
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [ { provide: LOCALE_ID, useValue: 'hi' } ],
bootstrap: [AppComponent]
})
export class AppModule { }
Here,
Import the locale data from @angular/common/locales/hi and then, register it using
registerLocaleData method as specified below:
registerLocaleData(localeHi);
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
Page 175 of 255
Create a local variable, CurrentDate and set current time using [Link]().
Change AppComponents template content and include the currentDate as specified below
−
<div>Hello</div>
<div>The Current time is {{ currentDate | date : 'medium' }}</div>
Check the result and you will see the date is specified using hi locale.
We have changed the date to current locale. Let us change other content as well. To do
it, include i18n attribute in the relevant tag with format, title|description@@id.
Here,
</trans-unit>
<trans-unit id="currentTime" datatype="html">
<source>
The Current time is <x id="INTERPOLATION" equiv-text="
{{ currentDate | date : 'medium' }}"/>
</source>
<context-group purpose="location">
<context context-
type="sourcefile">src/app/[Link]</context>
<context context-type="linenumber">5</context>
Page 177 of 255
</context-group>
<note priority="1" from="description">Specifiy the current
time</note>
<note priority="1" from="meaning">time</note>
</trans-unit>
</body>
</file>
</xliff>
Open the file with Unicode text editor. Locate source tag and duplicate it with target tag
and then change the content to hi locale. Use google translator to find the matching
text. The changed content is as follows −
Open [Link] and place below configuration under build -> configuration
"hi": {
"aot": true,
"outputPath": "dist/hi/",
"i18nFile": "src/locale/[Link]",
"i18nFormat": "xlf",
"i18nLocale": "hi",
"i18nMissingTranslation": "error",
"baseHref": "/hi/"
},
"en": {
"aot": true,
"outputPath": "dist/en/",
"i18nFile": "src/locale/[Link]",
"i18nFormat": "xlf",
"i18nLocale": "en",
"i18nMissingTranslation": "error",
"baseHref": "/en/"
}
Page 178 of 255
Here,
"hi": {
"browserTarget": "i18n-sample:build:hi"
},
"en": {
"browserTarget": "i18n-sample:build:en"
}
We have added the necessary configuration. Stop the application and run below
command −
Here,
Navigate to [Link] and you will see the Hindi localised content.
Angular - Accessibility
Page 179 of 255
While using attribute binding, use attr. prefix for ARIA attributes.
Use Angular material component for Accessibility. Some of the useful components
are LiveAnnouncer and cdkTrapFocu.
Use native HTML elements wherever possible because native HTML element
provides maximum accessibility features. When creating a component, select
native html element matching your use case instead of redeveloping the native
functionality.
Use NavigationEnd to track and control the focus of the application as it greatly
helps in accessibility.
Verify CLI
Before moving to Angular CLI commands, we have to ensure that Angular CLI is installed
on your machine. If it is installed, you can verify it by using the below command −
ng version
If CLI is not installed, then use the below command to install it.
New command
ng new <project-name>
Example
If you want to create CustomerApp then, use the below code −
ng new CustomerApp
Generate Command
It is used to generate or modify files based on a schematic. Type the below command
inside your angular project −
Page 181 of 255
ng generate
Or, you can simply type generate as g. You can also use the below syntax −
ng g
Lets understand some of the repeatedly used ng generate schematics in next section.
Create a component
Components are building block of Angular. To create a component in angular use the
below syntax −
ng g c <component-name>
For example, if user wants to create a Details component then use the below code −
ng g c Details
After using this command, you could see the below response −
Create a class
It is used to create a new class in Angular. It is defined below−
ng g class <class-name>
If you want to create a customer class, then type the below command −
ng g class Customer
After using this command, you could see the below response −
Create a pipe
Pipes are used for filtering the data. It is used to create a custom pipe in Angular. It is
defined below −
ng g pipe <pipe-name>
If you want to create a custom digit counts in a pipe, then type the below command −
ng g pipe DigitCount
After using this command, you could see the below response −
Create a directive
Page 183 of 255
ng g directive <directive-name>
If you want to create a UnderlineText directive, then type the below command −
ng g directive UnderlineText
After using this command, you could see the below response −
Create a module
It is used to create a new module in Angular. It is defined below −
ng g module <module-name>
If you want to create a user information module, then type the below command −
ng g module Userinfo
After using this command, you could see the below response −
Create an interface
ng g interface <interface-name>
If you want to create a customer class, then type the below command −
ng g interface CustomerData
Page 184 of 255
After using this command, you could see the below response −
ng g webWorker <webWorker-name>
If you want to create a customer class, then type the below command −
ng g webWorker CustomerWebWorker
After using this command, you could see the below response −
Create a service
ng g service <service-name>
If you want to create a customer class, then type the below command −
ng g service CustomerService
After using this command, you could see the below response −
Create an enum
Page 185 of 255
ng g enum <enum-name>
If you want to create a customer class, then type the below command −
ng g enum CustomerRecords
After using this command, you could see the below response −
Add command
It is used to add support for an external library to your project. It is specified by the
below command −
ng add [name]
Build command
ng build
After using this command, you could see the below response −
Config command
It is used to retrieve or set Angular configuration values in the [Link] file for the
workspace. It is defined below −
ng config
After using this command, you could see the below response −
Page 186 of 255
{
"$schema": "./node_modules/@angular/cli/lib/config/[Link]",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"MyApp": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
.............................
.............................
Doc command
It is used to open the official Angular documentation ([Link]) in a browser, and
searches for a given keyword.
ng doc <keyword>
For example, if you search with component as ng g component then, it will open the
documentation.
e2e command
It is used to build and serves an Angular app, then runs end-to-end tests using
Protractor. It is stated below −
Help command
It lists out available commands and their short descriptions. It is stated below −
ng help
Serve command
Page 187 of 255
It is used to build and serves your app, rebuilding on file changes. It is given below: −
ng serve
Test command
ng test
Update command
Updates your application and its dependencies. It is given below −
ng update
Version command
ng version
Angular - Testing
Testing is a very important phase in the development life cycle of an application. It
ensures an application quality. It needs careful planning and execution.
Unit Test
Unit testing is the easiest method to test an application. It is based on ensuring the
correctness of a piece of code or a method of a class. But, it does not reflect the real
environment and subsequently. It is the least option to find the bugs.
Generally, Angular uses Jasmine and Karma configurations. To perform this, first you
need to configure in your project, using the below command −
ng test
Now, Chrome browser also opens and shows the test output in the Jasmine HTML
Reporter. It looks similar to this,
ng e2e
Optimised code.
Better performance.
Open [Link] and set the aot option (projects -> -> architect -> build ->
configurations -> production) of the project to true.
{
"projects": {
"my-existing-project": {
"architect": {
"build": {
"options": {
...
"aot": true,
}
}
}
}
}
}
{
...
Page 191 of 255
"angularCompilerOptions": {
"enableIvy": true
}
Compile and run the application and get benefited by Ivy Compiler.
Angular supports building the application using bazel. Let us see how to use bazel to
compile Angular application.
ng add @angular/bazel
ng new --collection=@angular/bazel
ng build --leaveBazelFilesOnDisk
Here,
Page 192 of 255
leaveBazelFilesOnDisk option will leave the bazel files created during build process,
which we can use to build the application directly using bazel.
To build application using bazel directly, install @bazel/bazelisk and then, use bazelisk
build command.
Angular maintains documentation and guides of all version. For example, Angular
documentation for version 7 can be checked @ [Link] Angular also
provides a detailed upgrade path through [Link] site.
To update Angular application written from previous version, use below command inside
the project directory:
HttpModule module and its associated Http service is removed. Use HttpClient
service from HttpClientModule module.
Lazy loading string syntax in router module is removed and only function based is
supported.
Page 193 of 255
loadChildren: './lazy/[Link]#LazyModule'
loadChildren: () => import('./lazy/[Link]'
Let us create an Angular application to check our day to day expenses. Let us give
ExpenseManager as our choice for our new application.
Create an application
Use below command to create the new application.
cd /path/to/workspace
ng new expense-manager
Here,
new is one of the command of the ng CLI application. It will be used to create new
application. It will ask some basic question in order to create new application. It is
enough to let the application choose the default choices. Regarding routing question as
mentioned below, specify No.
Once the basic questions are answered, the ng CLI application create a new Angular
application under expense-manager folder.
cd expense-manager
ng serve
Let us fire up a browser and opens [Link] The browser will show the
application as shown below −
Page 194 of 255
Let us change the title of the application to better reflect our application. Open
src/app/[Link] and change the code as specified below −
Add a component
Create a new component using ng generate component command as specified below −
Output
The output is as follows −
Here,
@Component({
selector: 'app-expense-entry',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ExpenseEntryComponent implements OnInit {
title: string;
constructor() { }
ngOnInit() {
[Link] = "Expense Entry"
}
}
Open
src/app/[Link]
Here,
app-expense-entry is the selector value and it can be used as regular HTML Tag.
Include bootstrap
Let us include bootstrap into our ExpenseManager application using styles option and
change the default template to use bootstrap components.
cd /go/to/expense-manager
Here,
We have installed JQuery, because, bootstrap uses jquery extensively for advanced
components.
{
"projects": {
"expense-manager": {
"architect": {
"build": {
"builder":"@angular-devkit/build-angular:browser", "options": {
"outputPath": "dist/expense-manager",
"index": "src/[Link]",
"main": "src/[Link]",
Page 198 of 255
"polyfills": "src/[Link]",
"tsConfig": "[Link]",
"aot": false,
"assets": [
"src/[Link]",
"src/assets"
],
"styles": [
"./node_modules/bootstrap/dist/css/[Link]",
"src/[Link]"
],
"scripts": [
"./node_modules/jquery/dist/[Link]",
"./node_modules/bootstrap/dist/js/[Link]"
]
},
},
}
}},
"defaultProject": "expense-manager"
}
Here,
<span class="sr-only">(current)
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Report</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Add Expense</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</div>
</nav>
<app-expense-entry></app-expense-entry>
Here,
<strong><em>Item:</em></strong>
</div>
<div class="col" style="text-align: left;">
Pizza
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Amount:</em></strong>
</div>
<div class="col" style="text-align: left;">
20
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Category:</em></strong>
</div>
<div class="col" style="text-align: left;">
Food
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Location:</em></strong>
</div>
<div class="col" style="text-align: left;">
Zomato
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Spend On:</em></strong>
</div>
<div class="col" style="text-align: left;">
June 20, 2020
</div>
</div>
</div>
</div>
</div>
</div>
Page 201 of 255
We will improve the application to handle dynamic expense entry in next chapter.
Add an interface
Create ExpenseEntry interface (src/app/[Link]) and add id, amount,
category, Location, spendOn and createdOn.
ngOnInit() {
[Link] = "Expense Entry";
[Link] = {
id: 1,
item: "Pizza",
amount: 21,
category: "Food",
location: "Zomato",
spendOn: new Date(2020, 6, 1, 10, 10, 10),
createdOn: new Date(2020, 6, 1, 10, 10, 10),
};
}
}
{{ [Link] }}
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Location:</em></strong>
</div>
<div class="col" style="text-align: left;">
{{ [Link] }}
</div>
</div>
<div class="row">
<div class="col-2" style="text-align: right;">
<strong><em>Spend On:</em></strong>
</div>
<div class="col" style="text-align: left;">
{{ [Link] }}
</div>
</div>
</div>
</div>
Page 204 of 255
</div>
</div>
Using directives
Let us add a new component in our ExpenseManager application to list the expense
entries.
cd /go/to/expense-manager
ng serve
Output
The output is as follows −
Page 205 of 255
Here, the command creates the ExpenseEntryList Component and update the necessary
code in AppModule.
getExpenseEntries() : ExpenseEntry[] {
let mockExpenseEntries : ExpenseEntry[] = [
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
category: "Food",
location: "Mcdonald",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
10, 10, 10) },
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
category: "Food",
location: "KFC",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
10, 10, 10) },
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
Page 206 of 255
category: "Food",
location: "Mcdonald",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
10, 10, 10) },
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
category: "Food",
location: "KFC",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
10, 10, 10) },
{ id: 1,
item: "Pizza",
amount: [Link](([Link]() * 10) + 1),
category: "Food",
location: "KFC",
spendOn: new Date(2020, 4, [Link](([Link]() * 30) + 1), 10,
10, 10),
createdOn: new Date(2020, 4, [Link](([Link]() * 30) + 1),
10, 10, 10)
},
];
return mockExpenseEntries;
}
Declare a local variable, expenseEntries and load the mock list of expense entries as
mentioned below −
title: string;
expenseEntries: ExpenseEntry[];
constructor() { }
ngOnInit() {
[Link] = "Expense Entry List";
[Link] = [Link]();
}
Here,
Used bootstrap table. table and table-striped will style the table according to
Boostrap style standard.
Used ngFor to loop over the expenseEntries and generate table rows.
...
<app-expense-entry-list></app-expense-entry-list>
Use pipes
Let us use the pipe in the our ExpenseManager application
Here, we have used the date pipe to show the spend on date in the short format.
ng g service debug
This will create two Typescript files (debug service & its test) as specified below −
Here,
Page 210 of 255
providerIn option and its value, root enables the DebugService to be used in all
component of the application.
Let us add a method, Info, which will print the message into the browser console.
Here,
Calling the info method of DebugService in the ngOnInit method prints the
message in the browser console.
Page 211 of 255
The result can be viewed using developer tools and it looks similar as shown below −
// src/app/[Link]
import { Injectable } from '@angular/core'; @Injectable()
export class DebugService {
constructor() {
}
info(message : String) : void {
[Link](message);
Page 212 of 255
}
}
// src/app/expense-entry-list/[Link] @Component({
selector: 'app-expense-entry-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
providers: [DebugService]
})
Here, we have used providers meta data (ElementInjector) to register the service.
Here, we have not registered DebugService. So, DebugService will not be available if
used as parent component. When used inside a parent component, the service may
available from parent, if the parent has access to the service.
// existing content
<app-debug></app-debug>
<ng-content></ng-content>
Page 213 of 255
// navigation code
<app-expense-entry-list>
<app-debug></app-debug>
</app-expense-entry-list>
Let us check the application and it will show DebugService template at the end of the
page as shown below −
Also, we could able to see two debug information from debug component in the console.
This indicate that the debug component gets the service from its parent component.
Let us change how the service is injected in the ExpenseEntryListComponent and how
it affects the scope of the service. Change providers injector to viewProviders injection.
viewProviders does not inject the service into the content child and so, it should fail.
Page 214 of 255
viewProviders: [DebugService]
Check the application and you will see that the one of the debug component (used as
content child) throws error as shown below −
Let us remove the debug component in the templates and restore the application.
<app-debug></app-debug>
<ng-content></ng-content>
// navigation code
<app-expense-entry-list>
</app-expense-entry-list>
providers: [DebugService]
cd /go/to/expense-manager
ng serve
This will create two Typescript files (expense entry service & its test) as specified below
−
Create a variable, httpOptions to set the Http Header option. This will be used during
the Http Rest API call by Angular HttpClient service.
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class ExpenseEntryService {
private expenseRestUrl = 'api/expense';
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
constructor(
private httpClient : HttpClient) { }
}
cd /go/to/expense-rest-api
node .\[Link]
getExpenseEntries() : Observable<ExpenseEntry[]> {
return [Link]<ExpenseEntry[]>([Link],
[Link])
.pipe(retry(3),catchError([Link]));
}
Here,
getExpenseEntries() calls the get() method using expense end point and also
configures the error handler. Also, it configures httpClient to try for maximum of
3 times in case of failure. Finally, it returns the response from server as typed
(ExpenseEntry[]) Observable object.
@Injectable({
providedIn: 'root'
})
export class ExpenseEntryService {
private expenseRestUrl = '[Link]
private httpOptions = {
headers: new HttpHeaders( { 'Content-Type': 'application/json' })
};
getExpenseEntries() : Observable {
return [Link]([Link], [Link])
.pipe(
retry(3),
catchError([Link])
);
}
getExpenseItems() {
[Link]()
.subscribe( data =− [Link] = data );
}
@Component({
selector: 'app-expense-entry-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
providers: [DebugService]
})
export class ExpenseEntryListComponent implements OnInit {
title: string;
expenseEntries: ExpenseEntry[];
constructor(private debugService: DebugService, private restService :
ExpenseEntryService ) { }
ngOnInit() {
Page 220 of 255
[Link]();
}
getExpenseItems() {
[Link]()
.subscribe( data => [Link] = data );
}
}
Finally, check the application and you will see the below response.
);
}
Add Routing
Generate routing module using below command, if not done before.
Output
The output is mentioned below −
Here,
Here, we have added route for our expense list and expense details component.
Here, we have updated the expense list table and added a new column to show the view
option.
[Link]$ = [Link](
switchMap(params => {
[Link] = Number([Link]('id'));
return
[Link]([Link]); }));
[Link]$.subscribe( (data) => [Link] = data );
goToList() {
[Link](['/expenses']);
}
expenseEntry$ : Observable<ExpenseEntry>;
expenseEntry: ExpenseEntry = {} as ExpenseEntry;
selectedId: number;
constructor(private restService : ExpenseEntryService, private router :
Router, private route :
ActivatedRoute ) { }
ngOnInit() {
[Link] = "Expense Entry";
[Link]$ = [Link](
switchMap(params => {
[Link] = Number([Link]('id'));
return
[Link]([Link]); }));
[Link]$.subscribe( (data) => [Link] = data );
}
goToList() {
[Link](['/expenses']);
}
}
ng serve
Clicking the view option of the first entry will navigate to details page and show the
selected expense entry as shown below −
@Injectable({
providedIn: 'root'
})
export class AuthService {
return of([Link]).pipe(
delay(1000),
tap(val => {
[Link]("Is User Authentication is successful: " + val);
})
);
}
logout(): void {
[Link] = false;
[Link]('isUserLoggedIn');
}
constructor() { }
}
Here,
The purpose of the login method is to validate the user and if the user
successfully validated, it stores the information in localStorage and then returns
true.
Authentication validation is that the user name and password should be admin.
We have not used any backend. Instead, we have simulated a delay of 1s using
Observables.
The purpose of the logout method is to invalidate the user and removes the
information stored in localStorage.
@Component({
selector: 'app-login',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class LoginComponent implements OnInit {
userName: string;
password: string;
formData: FormGroup;
ngOnInit() {
[Link] = new FormGroup({
Page 229 of 255
onClickSubmit(data: any) {
[Link] = [Link];
[Link] = [Link];
[Link]([Link], [Link])
.subscribe( data => {
[Link]("Is Login Success: " + data);
if(data) [Link](['/expenses']);
});
}
}
Here,
(ngSubmit)="onClickSubmit([Link])"
class="form-signin">
<h2 class="form-signin-heading">Please
sign in</h2>
<label for="inputEmail" class="sr-
only">Email address</label>
<input type="text" id="username"
class="form-control"
formControlName="userName"
placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-
only">Password</label>
<input type="password" id="inputPassword"
class="form-control"
formControlName="password"
placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-
block" type="submit">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Here,
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
input {
Page 231 of 255
margin-bottom: 20px;
}
@Component({
selector: 'app-logout',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class LogoutComponent implements OnInit {
ngOnInit() {
[Link]();
[Link](['/']);
}
Here,
Page 232 of 255
Once the user is logged out, the page will redirect to home page (/).
@Injectable({
providedIn: 'root'
})
export class ExpenseGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree {
let url: string = [Link];
return [Link](url);
}
else
return true;
} else {
return [Link]('/login');
}
}
}
Here,
checkLogin will check whether the localStorage has the user information and if it
is available, then it returns true.
If the user is logged in and goes to login page, it will redirect the user to
expenses page
If the user is not logged in, then the user will be redirected to login page.
@NgModule({
Page 234 of 255
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here,
Created two new routes, login and logout to access LoginComponent and
LogoutComponent respectively.
Open AppComponent template and add two login and logout link.
</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/expenses">Report</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Add Expense</a>
</li>
<li class="nav-item">
<ng-template #isLogOut>
<a class="nav-link"
Page 235 of 255
routerLink="/login">Login</a>
</ng-template>
</li>
</ul>
</div>
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
ngOnInit() {
let storeData = [Link]("isUserLoggedIn");
[Link]("StoreData: " + storeData);
[Link] = false;
}
}
Here, we have added the logic to identify the user status so that we can show login /
logout functionality.
Now, run the application and the application opens the login page.
Enter admin and admin as username and password and then, click submit. The
application process the login and redirects the user to expense list page as shown below
−
Page 237 of 255
@Component({
selector: 'app-edit-entry',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class EditEntryComponent implements OnInit {
id: number;
item: string;
amount: number;
category: string;
location: string;
spendOn: Date;
formData: FormGroup;
selectedId: number;
expenseEntry: ExpenseEntry;
ngOnInit() {
[Link] = new FormGroup({
id: new FormControl(),
item: new FormControl('', [[Link]]),
amount: new FormControl('', [[Link]]),
category: new FormControl(),
location: new FormControl(),
spendOn: new FormControl()
});
[Link] = Number([Link]('id'));
[Link]['category'].setValue([Link].c
[Link]['location'].setValue([Link].l
[Link]['spendOn'].setValue([Link]
})
}
get itemValue() {
return [Link]('item');
}
get amountValue() {
return [Link]('amount');
}
onClickSubmit(data: any) {
[Link]('onClickSubmit fired');
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
Here,
Created two methods, itemValue and amountValue to get the item and
amount values respectively entered by user for the validation purpose.
Created method, onClickSubmit to save (add / update) the expense entry.
<div class="form-group">
<label for="amount">Amount</label>
<input type="text" class="form-control" id="amount" formControlName="amount">
<div
*ngIf="!amountValue?.valid && (amountValue?.dirty ||amountValue?.touched)">
<div [hidden]="![Link]">
Amount is required
</div>
</div>
</div>
<div class="form-group">
<label for="category">Category</label>
<select class="form-control" id="category" formControlName="category">
<option>Food</option>
<option>Vegetables</option>
<option>Fruit</option>
<option>Electronic Item</option>
<option>Bill</option>
</select>
</div>
<div class="form-group">
<label for="location">location</label>
<input type="text" class="form-control" id="location" formControlName="locati
</div>
<div class="form-group">
<label for="spendOn">spendOn</label>
<input type="text" class="form-control" id="spendOn" formControlName="spendOn
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="!formD
</form>
</div>
</div>
</div>
</div>
Here,
Created a form and bind it to the form, formData created in the class.
.form {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form label {
text-align: left;
width: 100%;
}
input {
margin-bottom: 20px;
}
@Component({
selector: 'app-about',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AboutComponent implements OnInit {
title = "About";
constructor() { }
Page 243 of 255
ngOnInit() {
}
Add routing for add and edit expense entries as specified below
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here, we have added about, add expense and edit expense routes.
Here, we have included two more columns. One column is used to show edit link and
another to show delete link.
deleteExpenseEntry(evt, id) {
[Link]();
if(confirm("Are you sure to delete the entry?")) {
[Link](id)
.subscribe( data => [Link](data) );
[Link]();
}
}
Here, we have asked to confirm the deletion and it user confirmed, called the
deleteExpenseEntry method from expense service to delete the selected expense item.
Change
Edit link in the ExpenseEntryListComponent template at the top to Add link
as shown below −
(click)="goToEdit()">Edit</button>
</div>
goToEdit() {
[Link](['/expenses/edit', [Link]]);
}
<ng-template #isLogOut>
<a class="nav-link"
Page 247 of 255
routerLink="/login">Login</a>
</ng-template>
</li>
</ul>
</div>
</div>
</nav>
<router-outlet></router-outlet>
Here, we have updated the add expense link and about link.
Run the application and the output will be similar as shown below −
Try to add new expense using Add link in expense list page. The output will be similar as
shown below
Page 248 of 255
If the data is not filled properly, the validation code will alert as shown below −
Page 249 of 255
Click Submit. It will trigger the submit event and the data will be saved to the backend
and redirected to list page as shown below −
Try to edit existing expense using Edit link in expense list page. The output will be similar
as shown below −
Page 250 of 255
Click Submit. It will trigger the submit event and the data will be saved to the backend
and redirected to list page.
To delete an item, click delete link. It will confirm the deletion as shown below −
Install Angular 9
If you want to work with Angular 9, first you need to setup Angular 9 CLI using the
below command:
After executing this command, you can check the version using the below command:
ng version
Angular 9 Updates
Lets understand Angular 9 updates in brief.
Ivy compiler
Ivy compiler becomes the default compiler in Angular 9. This makes apps will be faster
and very efficient. Whereas, Angular Ivy is optional. We have to enable it inside
[Link] file.
Improved CSS class and styles − Ivy styles are easily merged and designed as
predictable.
Improved type checking − This feature helps to find the errors earlier in
development process.
Enhanced debugging − Ivy comes with more tools to enable better debugging
features. This will be helpful to show useful stack trace so that we can easily
jump to the instruction.
Reliable ng update
ng updates are very reliable. It contains clear progress updates and runs all of the
migrations. This can be done using the below command:
Page 252 of 255
ng update --create-commits
Here,
@Injectable({
providedIn: 'platform'
})
class MyService {...}
TypeScript 3.8
Angular 9 is designed to support 3.8 version. TypeScript 3.8 brings support for the below
features:
Top-Level await.
export * as ns Syntax.
Angular 9.0.0-next.5
Angular 9.0.0-next.5 build has small size of [Link] file, which makes better
performance compare to previous version of Angular.
IDE enhancement
Angular 9 provides imporves IDE supports. TextMate grammar enables for syntax
highlighting in inline and external templates.
Conclusion
Page 253 of 255
TOP TUTORIALS
Python Tutorial
Java Tutorial
C++ Tutorial
C Programming Tutorial
C# Tutorial
PHP Tutorial
R Tutorial
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
SQL Tutorial
TRENDING TECHNOLOGIES
Git Tutorial
Ethical Hacking Tutorial
Docker Tutorial
Kubernetes Tutorial
DSA Tutorial
Spring Boot Tutorial
SDLC Tutorial
Unix Tutorial
CERTIFICATIONS