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

Learn Angular Step by Step: (Covering Angular 2 and Angular 4)

Uploaded by

blr 1989
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

Learn Angular Step by Step: (Covering Angular 2 and Angular 4)

Uploaded by

blr 1989
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Learn Angular step by step

(Covering Angular 2 and Angular 4)

By

www.questpond.com

Version 2.0

Contents
Introduction ............................................................................................................................................ 4
Who wrote this book? ............................................................................................................................ 4
How does this book teach you Angular ?................................................................................................ 5
Why do we need Angular ? ..................................................................................................................... 6
Lab 1:- Practicing NodeJS ........................................................................................................................ 8
Theory :- What is NodeJS ? ................................................................................................................. 8
Step 1 :- Installing NodeJs ................................................................................................................... 9
Step 2:- Practicing NPM Install command........................................................................................... 9
Step 3:- Understanding package.json file ......................................................................................... 10
Lab 2:- Practicing TypeScript ................................................................................................................. 11
Introduction :- Why do we need typescript ? ................................................................................... 11
Step 1 :- Installing typescript ............................................................................................................ 12
Step 2 :- Compiling a simple Typescript to Javascript ....................................................................... 12
Step 3 :- Using tsconfig.json file ....................................................................................................... 13
Lab 3:- Practicing VS Code..................................................................................................................... 14
What is VS Code? .............................................................................................................................. 14
Point number 1 :- All actions happens in a folder ............................................................................ 14
Point number 2 :- Creating files and folders ..................................................................................... 15
Point number 3 :- Explorer and Open Editors ................................................................................... 15
Point number 4:- Reveal in explorer ................................................................................................. 16
Point number 5: - Integrated terminal.............................................................................................. 16
Lab 4:- Understanding Module loaders using SystemJs....................................................................... 17
Step 1 :- TypeScript Modules and Import / Export keywords .......................................................... 17
Step 2 :- Module formats in JavaScript CommonJS , AMD , ES6 ....................................................... 18
Step 3 :- Calling Javascript module loaders in HTML UI .................................................................... 21
Lab 5:- Components and Modules ( Running your first Angular Application) ...................................... 23
Introduction ...................................................................................................................................... 23
Step 1:- NPM install to get Angular framework ................................................................................ 24
Step 2:- Typescript configuration tsconfig.json ................................................................................ 26
Step 3:- Configuring SystemJS module loader .................................................................................. 27
Step 4:- Configuring the task runner ................................................................................................. 28
Understanding Angular Component and module architecture ........................................................ 30
Step 5:- Following MVW Step by Step – Creating the folders .......................................................... 31
Step 6:- Creating the model .............................................................................................................. 32
Step 7:- Creating the Component ..................................................................................................... 33
Step 8:- Creating the Customer HTML UI – Directives and Interpolation ......................................... 36
Step 9:- Creating the Module............................................................................................................ 37
Step 10:- Creating the “Startup.ts” file ............................................................................................. 39
Step 11:- Invoking “Startup.ts” file using main angular page ........................................................... 39
Step 12:- Installing http-server and running the application ............................................................ 41
How to the run the source code? ..................................................................................................... 42
Lab 6:- Implementing SPA using Angular routing ................................................................................. 42
Fundamental of Single page application ........................................................................................... 42
Step 1 :- Creating the Master Page ................................................................................................... 43
Step 2:- Creating the Supplier page and welcome page .................................................................. 44
Step 3:- Renaming placeholder in Index.html................................................................................... 45
Step 4:- Removing selector from CustomerComponent................................................................... 45
Step 5:- Creating Components for Master , Supplier and Welcome page ........................................ 46
Step 6: - Creating the routing constant collection ............................................................................ 47
Step 7: - Defining routerLink and router-outlet ................................................................................ 49
Step 8:- Loading the routing in Main modules ................................................................................. 50
Step 9:- Seeing the output ................................................................................................................ 51
Step 10:- Fixing Cannot match any routes error ............................................................................... 52
Understanding the flow .................................................................................................................... 52
Lab 7 :- Implementing validation using Angular form .......................................................................... 53
Requirement of a good validation structure .................................................................................... 53
There are 3 broader steps to implement Angular validation ........................................................... 54
What kind of validation will we implement in this Lab ? .................................................................. 54
Where to put Validations ? ............................................................................................................... 54
Step 1 :- Import necessary components for Angular validators ....................................................... 55
Step 2 :- Create FormGroup using FormBuilder ............................................................................... 55
Step 3 :- Adding a simple validation.................................................................................................. 55
Step 4 :- Adding a composite validation ........................................................................................... 56
Full Model code with validation........................................................................................................ 56
Step 5 :- Apply formGroup to HTML form ........................................................................................ 57
Step 6:- Apply validations to HTML control ...................................................................................... 57
Step 7:- Check if Validations are ok .................................................................................................. 57
Step 8:- Checking individual validations ........................................................................................... 58
Step 9 :- standalone elements .......................................................................................................... 58
Complete code of Customer UI with validations applied ................................................................. 60
Run and see your validation in action ............................................................................................... 61
Dirty , pristine , touched and untouched .......................................................................................... 61
Lab 8 :- Making HTTP calls..................................................................................................................... 62
Importance of server side interaction .............................................................................................. 62
Yes , this is a pure Angular book ....................................................................................................... 62
Step 1 :- Creating a fake server side service ..................................................................................... 62
Step 2 :- Importing HTTP and WebAPI module in to main module .................................................. 64
Where do we put the HTTP call ? ..................................................................................................... 64
Step 3 :- Importing HTTP in the Customer component .................................................................... 65
Step 4:- Creating header and request information........................................................................... 65
Step 5 :- Making HTTP calls and observables .................................................................................... 66
Step 6 :- Creating a simple post and get call .................................................................................... 66
Step 7 :- Connecting components to User interface......................................................................... 68
Lab 9:- Input, Output and emitters ....................................................................................................... 69
Theory ............................................................................................................................................... 69
Planning how the component will look like ...................................................................................... 70
Step 1 :- Import input , output and Event Emitter ............................................................................ 70
Step 2 :- Creating the reusable GridComponent class ...................................................................... 70
Step 3 :- Defining inputs and output ................................................................................................. 71
Step 4 :- Defining Event emitters ...................................................................................................... 72
Step 5 :- Creating UI for the reusable component ............................................................................ 73
Step 6 :- Consuming the component in the customer UI ................................................................. 75
Step 7 :- Creating events in the main Customer component ........................................................... 75
Step 8 :- Defining the component in the mainmodule ..................................................................... 76
Lab 10:- Lazy loading using dynamic routes ......................................................................................... 76
Theory ............................................................................................................................................... 76
Step 1 :- Creating three different physical modules ........................................................................ 77
Step 2 :- Removing Supplier and Customercomponent from MainModule ..................................... 78
Step 3 :- Creating different Route files ............................................................................................. 79
Step 4 :- Calling Child routes in Supplier and Customer modules .................................................... 82
Step 5 :- Configuring routerlinks ....................................................................................................... 83
Step 6 :- Replacing browser module with common module ............................................................ 84
Step 7 :- Check if Lazy loading is working ......................................................................................... 86
Acronym used in this book.................................................................................................................... 87

Introduction

Why should we learn Angular? , the below stack overflow graph says it all. Its popular, its hot with
lot of job openings. This book teaches your Angular step by step via 10 great Labs. So if you are here
to learn Angular then you are at the right place and with the right book.

AngularJS vs Angular. There are two versions of Angular the old is named as AngularJS and the
new one is name as just Angular. So when someone says AngularJS it means Angular 1.X and
when some says JUST Angular its Angular 2/4.

Who wrote this book?

My name is Shivprasad Koirala, a 40 years old selfish developer and author 😊. He steals times
from his kids and family to write books 😊. You can catch his Learn Angular in 8 hours step by step
video series from https://www.youtube.com/watch?v=oMgvi-AV-eY

He feeds himself by recording training videos on www.questpond.com and also has an institute in
Andheri Mumbai where he takes training on Angular in weekly basis. Any technical / non-technical
issues with this book please feel to contact him on [email protected]

Please do boost my EGO 😊 by tagging me on my facebook profile at


https://www.facebook.com/shivprasad.koirala , it just motivates us to write more.
How does this book teach you Angular ?

The best way to learn Angular or any new technology is by creating a project. So in this step by step
series we will be creating a simple Customer data entry screen project.

This project will have the following features:-

 Application should have capability of accepting three fields Customer name , Customer and
Customer Amount values.
 Customer name and Customer codes are compulsory fields and it should be validated.
 Application will have a “Add” button which help us to post the current customer data to a
Server. Once the data is added to the server it should displayed on the grid.
 Application will have a navigation structure where in we will have logo and company name
at the top , navigational link at the left and copy right details at the bottom of the screen.
So above is the road map of this book. It has three phases: -

Theory Phase :- In this phase we will understand what is Angular and why do we need it.

Pre-requiste phase :-In this phase we will four important things Node , Typescript , VSCode and
Module loaders ( systemJS).

Main learning phase :- This is where actual angular starts.In this we will be having 7 labs and while
covering those labs we will creating the customer data entry screen project as discussed previously.

So do not wait any more start LAB by LAB and STEP by STEP.

Should I start from Angular 1, 2 or 4. Angular 1.X and 2.X are very much different. So even if
you have done Angular 1.X you have to restart fresh from Angular 2.X. Angular 2.X and Angular
4.X are backward compatible so if you are learning Angular 2 you are learning Angular 4 and ahead.
So people who are new to Angular just start from Angular 4 and this book teaches Angular 4.

Why do we need Angular ?

“Angular is an open source JavaScript framework which simplifies binding code between JavaScript
objects and HTML UI elements.”
Let us try to understand the above definition with simple sample code.
Below is a simple “Customer” function with “CustomerName” property. We have also created an object
called as “Cust” which is of “Customer” class type.

function Customer()
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();

Now let us say in the above customer object we want to bind to a HTML text box called as
“TxtCustomerName”. In other words when we change something in the HTML text box the customer
object should get updated and when something is changed internally in the customer object the UI
should get updated.

<input type=text id="TxtCustomerName" onchange="UitoObject()"/>

So in order to achieve this communication between UI to object developers end up writing functions as
shown below. “UitoObject” function takes data from UI and sets it to the object while the other function
“ObjecttoUI” takes data from the object and sets it to UI.

function UitoObject()
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi()
{
$("#TxtCustomerName").val(Cust.CustomerName);
}

So if we analyze the above code visually it looks something as shown below. Your both functions are
nothing but binding code logic which transfers data from UI to object and vice versa.

Binding Code

Now the same above code can be written in Angular as shown below. So now whatever you type in the
textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the
UI.

<input type=text [(ngModel)]="Customer.CustomerName"/>

In short if you now analyze the above code visually you end up with something as shown in the below
figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions
and the binding code in Angular.
Now that binding code have different vocabularies.
 Some developers called it “ViewModel” because it connects the “Model” and the “View” .
 Some call it “Presenter” because this logic is nothing but presentation logic.
 Some term it has “Controller” because it controls how the view and the model will communicate.
To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that
“Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers
saying Angular implements “MVW” architecture.
So concluding the whole goal of Angular is Binding, Binding and Binding.

Lab 1:- Practicing NodeJS

So the first Javascript open source which you should know before learning Angular is NodeJS. In this
lab whatever I am adding is also demonstrated in this youtube video as well
https://www.youtube.com/watch?v=-LF_43_Mqnw, so feel free to see demonstrative lab.

Theory :- What is NodeJS ?

NodeJS is an open source JavaScript framework which does two things: -

 It helps you to run JavaScript outside the browser. NodeJS uses the chrome JavaScript
engine to execute JavaScript outside the browser so that we can create desktop and server
based application using JavaScript.
 It also acts a central repository from where we can get any JavaScript framework using NPM
(Node package manager).

Learn but do not over learn. NodeJS is a big topic by itself. For Angular we just need to know
how to use NPM commands. So we will be limiting ourselves only around how to use NPM. We
will not be doing full-fledged node programming. Remember Javascript is vast do not do
unnecessary learning you will loose focus.
Step 1 :- Installing NodeJs

In order to install NodeJS goto https://nodejs.org/ and download the latest version and install it.

Once you install node you should see NodeJs


command prompt in your program files as
shown in the figure.

We can then open the NodeJS command


prompt and fire NPM commands inside this
command prompt.

In case you are completely new to NodeJS


please see this NodeJS Video which explains
NodeJS in more details.

Step 2:- Practicing NPM Install command

So let’s practice the first command in NPM


“npm install”. “npm install” command helps
you get the latest version of any javascript
opensource framework.

For example if you want to install jquery you


will open node command prompt and type
“npm install jquery” and once you press enter
you should see “jquery” has been installed in
your computer.
Are you wondering where has Jquery
been installed. It has been installed in
the same folder where you ran the NPM
command.

In that folder he has created a


“node_modules” folder and in that he
has created “jquery” folder where all
Jquery had been loaded by “npm”.

Step 3:- Understanding package.json file

When you work with large projects you would need lot of JavaScript frameworks. So in one project
you would probably need jquery , angular , lodash and so on. Doing “npm install” again and again is
definitely wasting precious time of your life.
So to load all javascript framework references in one go “npm” team has given a package.json. In this
package.json file you can make an entry to all javascript references and load them in one go.

To create package.json file open the node command prompt and type “npm init”. After “npm init”
command it would ask for package name , version number , project description and so on. Once you
fill all the question it will create a package.json file in your current folder. Below is how “npm init”
command looks like.

Once npm init command has been successfully executed it creates a “package.json” file in the
current folder. If you open “package.json” file it has the following below structure.

Do not overload yourself with all the information just zoom on the “dependencies” node. This node
has all JavaScript dependencies listed out with version number. So in our package.json file we have
all the dependencies listed down.

{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "MyClass.js",
"dependencies": {
"angular": "^1.6.5",
"jquery": "^3.2.1",
"knockout": "^3.4.2",
"lodash": "~4.17.4"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

Wherever “package.json” file is


created you just need to type “npm
install” command as shown in the
figure.

If you remember in package.json file


we had 3 JavaScript framework
dependencies listed those will be
installed one after another. You can
see in the image its stating “added 3
packages”.

Learn but do not over learn. Package.json has lot of configuration do not spend your stamina
in learning all those. As we do the labs ahead I will be walking through important ones. So
keep moving ahead with the chapters.

Lab 2:- Practicing TypeScript

Angular is created using typescript language. So if you are doing development with Angular
typescript is the way to go ahead.

Introduction :- Why do we need typescript ?

Now JavaScript is a great and WEIRD language. So in JavaScript if you want to do inheritance you
need to use prototype, it’s not a strongly typed language, there is no polymorphism and so on. So
when developers who come from C# and Java background it’s very difficult for them to get
acquainted with this weird language. People who come from C# and Java background use OOP
features a lot.

So to fill this GAP answer is “TypeScript”.

“TypeScript is a sugar-coated Object-oriented programming language over JavaScript.”


So in typescript we can write code using
keywords like “class” , “extends” ,
“interface” and so on.

Internally typescript will compile ( must be


right word would be “transpile”) in to pure
javascript code in terms of functions ,
closures and IIFE.

Please do watch this 1 hour Training video on TypeScript which explains Typescript in more detail.

Step 1 :- Installing typescript

So to install typescript we need to use


“npm”. Typescript is a javascript open
source framework so the best way to get it
installed is by using “npm”. So open node
command prompt and type “npm install
typescript -g”.

The “-g” command says that you can


execute typescript command from any
folder.

Step 2 :- Compiling a simple Typescript to Javascript

Let’s try to understand how can we compile a typescript to javascript. So lets create a simple
“Customer.ts” file with the following code.

class Customer{
}
Now open nodeJS command prompt and type
command ‘tsc “Customer.ts”’. Once you press
enter it will create “Customer.js” in the same
folder.
If you remember “tsc” was registered globally
during “npm install” command. So this “tsc”
command can be executed in any folder.

Below is the javascript output from typescript command line utility.

var Customer = (function () {


function Customer() {
}
return Customer;
}());

Many people term this conversion from typescript to JavaScript as “compiling”. Personally, I feel we
should call this process as “transpiling”.
Compiling converts from a higher level languages like C# , Java , C++ to machine language or some
intermediate language which cannot be read by humans. While transpiling converts from one higher
level language to another higher-level language.

In this both typescript and JavaScript are higher level language. So let’s term this process and
transpiling and lets call typescript as a “transpiler” rather than a compiler.

Step 3 :- Using tsconfig.json file

The transpiling process of typescript has lot of advance settings. Below are some options you can
pass to tsc command line while compiling :-

Options Description
tsc Customer.ts –removecomments While transpiling the comments will be
removed
tsc Customer.ts --target ES5 This will compile using ES5 specifications.
tsc Customer.ts --outdir "c:\users\shiv" This will compile to a specific output directory
tsc foo.ts bar.ts –outFile “Single.js” This will compile multiple TS files to single JS
file.
But now let’s think practically, if I want transpile with ES5 specification, to a specific directory with
out comments the command line would become something as shown below.

tsc Customer.ts --outdir "c:\users\shiv" --target ES5 --removecomments

That’s where tsconfig.json file comes to rescue. You can put all these configurations in
“tsconfig.json” file and then just execute “tsc”.
{
"compilerOptions": {
"target": "es5",
"removeComments": false,
"outDir": "/Shiv"
}
}

Learn but do not over learn. Tsconfig.json has 1000’s of properties do not spend your
stamina in understanding all of them now. Move ahead with the labs when any new
typescript config comes up we will look in to it.

Lab 3:- Practicing VS Code

What is VS Code?

Theoretically you can do Angular with a simple notepad. But then that would be going back to back
ages of adam and eve and reinventing the wheel. So we will need some kind of tools by which will
help us to type HTML easily, compile typescript and so on.

That’s where VS code is needed. VS code is a free editor provided by Microsoft which will help us
with all automation for HTML, JavaScript, Typescript and so on.

So go to https://code.visualstudio.com/download and depending on your operating system install


the appropriate one. For instance I am having windows OS so I will be installing the windows version.

Once you download the setup it’s a simple setup EXE run it and just hit next , next and finish.

You can also watch this VS code tutorial which will help you to understand
https://www.youtube.com/watch?v=gQ9CiRlRPKs

Point number 1 :- All actions happens in a folder

In VS code all source code you put inside a folder. So the first step is to create a folder and point VS
code to that folder by clicking on File  Open and select folder shown in the below figure.
Point number 2 :- Creating files and folders

If you want to create a file or sub folder you can


click on the icons as shown in the figure.

The first icon creates a file and the second icon


creates a folder.

Point number 3 :- Explorer and Open Editors

The explorer part of VS code has two section one which shows open editors and the other which
shows your folder. You can see the image where open editors are shown. You can click on those
cross signs to close the open files.
Point number 4:- Reveal in explorer

If you want to browse to the current folder.You can right click on the folder and click on reveal in
explorer.

Point number 5: - Integrated terminal

Typescript, Node these frameworks mostly run through command prompts. So it would be great if
we can have integrated command line inside VS code. VS code has something called as integrated
terminal , you can open the integrated terminal by clicking on view  integrated terminal.

Once you are inside the integrated terminal you can fire “npm install” , “tsc” and so on. Below is how
the integrated terminal looks like.
Lab 4:- Understanding Module loaders using SystemJs

You can watch the below videos which demonstrates concept of Module Loaders and SystemJS
practically.

Topic name YouTube URL source


System JS https://www.youtube.com/watch?v=nQGhdoIMKaM
Common JS concept https://www.youtube.com/watch?v=jN4IM5tp1SE

Step 1 :- TypeScript Modules and Import / Export keywords

Modular development is one of the important pillars of development. A good software will always
have self-contained modules.

So you would like to create separate physical typescript or JavaScript files which will have self-
contained code. Then you would like have to some kind of reference mechanism by which modules
can be referred between those physical files.

In typescript, we do this by using “import” and


“export” keywords.

So the modules which needs to be exposed


should have the “export” keyword while
modules which want to import the exported
modules should have “import” keyword.
For instance, let’s say we have two typescript
files “Customer.ts” and “Dal.ts”. Let’s assume
“Customer.ts” is using “Dal.ts”.

So “Dal.ts” will use export to expose his


modules while “Customer.ts” will use to import
to get the exported module.

So in “Dal.ts” the classes which you want to export should be marked as “exported” as shown in the
below code. If you do not mark it exported it cannot be imported.

export class Dal{


Add(){
alert("Dal add called");
}
}

Now in the “Customer.ts” we use “import” to call the exported class from the “Dal.ts”.

import {Dal} from "./Dal "


export class Customer{
Add(){
var dal = new Dal();
dal.Add();

}
}

So in short you use export and import to do modular development in typescript. But now how does
this “TRANSPILE” to javascript code that we will see in the next section. At the end of the day all
these modules are transpiled to javascript so lets understand how that works under the hoods.

Step 2 :- Module formats in JavaScript CommonJS , AMD , ES6

Let’s first define this word “Module” formats. We talked about modules in the previous section.
Module formats define the JavaScript syntaxes of how the module should be exported and
imported.

In JavaScript world there are two ways of defining module formats: - UnOfficial way and Official way.
So prior to ES6 there was no official way so some of the unofficial viral ways of defining module
formats are CommonJs , AMD , UMD and so on. Official way is only and only one ES6.
For instance, below is the format of commonJS. In commonJS the module which is exported is
defined in “exports” variables and to import we need to use “require” keyword.

You can see below is the JS output where the dal is exported using “exports” variable.

Object.defineProperty(exports, "__esModule", { value: true });


var Dal = (function () {
function Dal() {
}
Dal.prototype.Add = function () {
alert("Dal add called");
};
return Dal;
}());
exports.Dal = Dal;

Below is the code for “Customer.js” which uses “require” to load “Dal.js”.

Object.defineProperty(exports, "__esModule", { value: true });


var Dal_js_1 = require("./Dal.js");
var Customer = (function () {
function Customer() {
}
Customer.prototype.Add = function () {
var dal = new Dal_js_1.Dal();
dal.Add();
};
return Customer;
}());
exports.Customer = Customer;

So now this is a commonJS format in the same way we have other formats as well. For example
below is “amd” module format.
In this we export the classes in the “export” variable and use “define” to import. Below is the code of
“define”. We are not pasting of “export” as its same like commonJS.

define(["require", "exports", "./Dal.js", "./Validation.js"], function


(require, exports, Dal_js_1, Validation_js_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Customer = (function () {
function Customer() {
}
Customer.prototype.Add = function () {
var val = new Validation_js_1.Validation();
var dal = new Dal_js_1.Dal();
dal.Add();
};
return Customer;
}());
exports.Customer = Customer;
});

In “ES6” module format to expose the class we need to “export” keywords and to consume we need
to use “import”.

import { Dal } from "./Dal.js";


import { Validation } from "./Validation.js";
var Customer = (function () {
function Customer() {
}
Customer.prototype.Add = function () {
var val = new Validation();
var dal = new Dal();
dal.Add();
};
return Customer;
}());
export { Customer };

var Dal = (function () {


function Dal() {
}
Dal.prototype.Add = function () {
alert("Dal add called");
};
return Dal;
}());
export { Dal };

So in simple words “amd” ,”commonJS” and “ES6” define how modules will communicate with each
other. Concluding ES6 uses “import / export” , amd uses “define/export” and commonJs uses
“require/export”.

All these module formats can be generated


with simple a option change in typescript config
file.

So in “tsconfig.json” we can set in “module”


which module format we want.

Step 3 :- Calling Javascript module loaders in HTML UI

Now when we try to load JavaScript functions which are using module formats like AMD , CommonJS
or ES6 it’s not so easy. For example in below code in HTML UI we have loaded “Dal.js” and
“Customer”.js”. This example has been demonstrated in the previous lab and is having “CommonJS”
enabled.
Also we have put the sequence properly , first we have added reference of “Dal.js” and then
“Customer.js” because “Customer.js” is dependent on “Dal.js”.

But When we try to create “Customer” object and try to call “Add” it does not work.

<script src="Dal.js"></script>
<script src="Customer.js"></script>
<script>
var cust = new Customer();
cust.Add();
</script>

We end up with an error below stating that “exports” is not understood. That makes sense because
browser does not know any keywords like “exports” and “require” as its not standard javascript.

The second problem is even if this code had worked i would still have ordering problems for large
number of references. Lets say we have 15 modules which are referencing using module formats we
would end with spending half-life arranging those sequences in HTML file. It would be great if we
can just point to “Customer.js” and automatically using “exports” and “imports” the references is
identified and “Address.js” is loaded.

That’s where we need Javascript module loaders. Some example of module loaders are SystemJS ,
WebPack and so on.

So if we are using module loaders we just


need to point to the first JS file and
automatically using the
“import/require/define” and “exports” it will
get references of all the dependent JS files
and load them accordingly.

Lets demonstrate a module using “SystemJS”. So first goto Node command prompt and install
“systemjs”.

npm install systemjs


So in the HTML UI we need to tell “system.js” which is the first JS file to be loaded. You can see in the
below code we are saying “SystemJS.import” load “Customer.js” as the first file.

<script src="system.js"></script>
<script>

SystemJS.import('./Customer.js')
.then(function(module){
var cust = new module.Customer();
cust.Add();
}).catch(function (err)
{ console.error(err); });;
</script>

Once the file has been loaded in the then function we get the modules. We can then refer the
module variable and create object of “Customer” function.

If you watch the network tab of chrome browser you can see first “system.js” loads “Customer.js”
and then also loads its reference that is “Dal.js”.

Lab 5:- Components and Modules ( Running your first Angular Application)

Introduction

In this lab we will configure Angular environment and we will try to create the basic Customer screen
and make it up and running. So lets start with the first step downloading angular framework and
configuring typescript compiler.
Step 1:- NPM install to get Angular framework

So lets create a folder called as “Angular” and open the same using VS code. Please refer Lab 3 on
how to use VS code. In case you want to Angular using visual studio you can see this video
https://www.youtube.com/watch?v=oMgvi-AV-eY . If you are eclipse guy please mail me at
[email protected]

So as we discussed in Lab 1 that “Node” has “npm” which helps us to get JavaScript open sources.
So create a package.json file with the below details and do a “npm install” in the integrated
command line of VS code.

{
"name": "angular-quickstart",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/upgrade": "4.0.0",
"angular2-in-memory-web-api": "0.0.20",
"bootstrap": "^3.3.6",
"core-js": "^2.4.1",
"http-server": "^0.10.0",
"reflect-metadata": "^0.1.3",
"rxjs": "^5.4.1",
"systemjs": "0.19.27",
"zone.js": "^0.6.23"
},
"devDependencies": {
"@types/core-js": "^0.9.42",
"typescript": "2.3.4"
}
}

If all the npm install runs successfully you


should see a node_modules folder in your VS
code project directory with the following folder
structure.

If you go inside the “Angular” folder you will


see lot of folders like common , http , forms
core and so on. Putting in simple words Angular
is MODULAR.

They have developed isolated components for


Forms , Http , Core and so on.

In AngularJS 1.X we just had one JS file which had the whole framework. So you drag and drop that
single Angular 1.X JS file on HTML page and you are ready with the Angular 1.X environment. But
the problem with having whole framework in one JS files was that you have to include all features
even if you need it or not.

For instance if you are not using HTTP still that feature will be loaded. In case of Angular we have
separate discrete components which makes Angular awesome.
Step 2:- Typescript configuration tsconfig.json

Also in the same folder we need to create tsconfig.json which defines how typescript will compile.
Do not worry on what settings are there in it we will explain as we go ahead. Remember do not
OVER LEARN. For now just note that the below file defines how TSC will compile.

{
"compilerOptions": {
"target": "es5",//defines what sort of code ts generates, es5 because
it's what most browsers currently UNDERSTANDS.
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,//for angular to be able to use metadata
we specify in our components.
"experimentalDecorators": true,//angular needs decorators like
@Component, @Injectable, etc.
"removeComments": false,
"noImplicitAny": false,
"noStrictGenericChecks": true,
"lib": ["es2016", "dom"]

}
}
Step 3:- Configuring SystemJS module loader

SystemJS file defines configuration of how SystemJS will load the frameworks. So this file put it in the
same folder with the name “systemjs.config.js”. The name should be EXACTLY “systemjs.config.js”
because systemJS looks with that name.

/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': '../node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'startup',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler':
'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-
browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-
browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'lodash':'node_modules/lodash',
// other libraries
'rxjs': 'npm:rxjs',
'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
'moment': 'npm:moment',
// ag libraries
'ag-grid-ng2': '../node_modules/ag-grid-ng2',
'ag-grid': '../node_modules/ag-grid',
'ng2-auto-complete': '../node_modules/ng2-auto-complete/dist'
},
// packages tells the System loader how to load when no filename
and/or no extension
packages: {
app: {
main: '../Startup/Startup.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
},
'lodash': { main: './index.js', defaultExtension: 'js' },
moment: {
defaultExtension: 'js'
},
'ag-grid-ng2': {
defaultExtension: "js"
},
'ag-grid': {
defaultExtension: "js"
},
'ng2-auto-complete': {
main: 'ng2-auto-complete.umd.js', defaultExtension: 'js'
}

}
});
})(this);

Step 4:- Configuring the task runner

VS Code is just a code editor. It has no idea how to compile typescript code, how to run TSC and so
on. So we need to create a GRUNT task which will run TSC command and transpile typescript code to
JavaScript.

Press CONTROL + SHIFT + B and click on configure task runner as shown in the below figure.

VS Code then pops up lot of task runner options saying what kind of task is it, is it a GRUNT task,
GULP task, MSBUILD, MAVEN etc. and so on.

Let’s select GRUNT Task and paste the below JSON code. Once you paste it you will see it has created
a file called as “tasks.json” file inside “.vscode” folder.

Below is the paste of “tasks.json” file. You can see in the command attribute we have given “tsc” as
the command line, the “isShellCommand” specifies that this has to be executed in command line and
‘args’ specifies the argument.

When typescript will execute it will run using the configuration specified in the tasks.json file.

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p","."],
"showOutput": "silent",
"problemMatcher": "$tsc"
}

So if you now press CONTROL + B it will build the TS files to JS file.

Understanding Angular Component and module architecture

As we said in the previous section that the whole goal of Angular is binding the model and the view.
In Angular the binding code is officially termed as “Component”. So hence forth we will use the word
“Component” for the binding code.

In enterprise projects you can have lot of components. With many components it can become very
difficult to handle the project. So you can group components logically in to modules.
So hence forth I will be using two terms:-

Components: - This will have the binding logic


to bind the UI and the model.

Modules :- This will logically group


components.

Step 5:- Following MVW Step by Step – Creating the folders

Before we start coding lets visualize the steps of coding. As we have said Angular is a binding
framework. It follows MVW architecture. It binds HTML UI with the JavaScript code (model).

So if we visualize it will look something as shown in the image below. So let’s move from right to
left. So let’s do the coding in the following sequence:-

1. Create the model.


2. Create the Component.
3. Create the module.
4. Create the HTML UI.

So let’s first create four folders in our project:-

 View folder: - This folder will contain the HTML UI.


 Model folder: - This folder will have the main business typescript classes.
 Component folder: - This folder will have the binding code which binds the HTML UI and
Model.
 Module: - This folder will have code which will logically group the components.

In order to create a folder in VS code you can use the “New folder” icon or you can right click and
also create a folder.

Step 6:- Creating the model


A model is nothing but a class with
properties and behavior. So let us first
create the customer model with three
properties “CustomerName”,
“CustomerCode” and
“CustomerAmount”.

So right click on the “Model” folder and


add a new file “Customer.ts”. Keep the
extension of this file as “.ts” as it’s a
typescript file.

While compiling the typescript


command identifies only files with the
extension “.ts”.

In the “Customer.ts” let’s create a “Customer” class with three properties. In this book we will not
be going through the basics of typescript , please do go through this 1 hour training video of
typescript which explains typescript in more detail.

export class Customer {


CustomerName: string = "";
CustomerCode: string = "";
CustomerAmount: number = 0;
}

Step 7:- Creating the Component

The next thing we need to code is the binding


code. Binding code in Angular is represented
by something termed as “COMPONENTS”.
Angular components has the logic which helps
to bind the UI with the model.

So right click on the component folder and add


“CustomerComponent.ts” file as shown in the
figure at the left.
In the component we need to import two things the Angular core and our Customer model. Please
note “import” is a typescript syntax and not JavaScript. So in case you are not following the code ,
please see this Learn Typescript in 1 hour video before moving ahead.

import {Customer} from '../Model/Customer'


import {Component} from "@angular/core"

The first line imports the “Customer” class in to the “CustomerComponent.ts”. This import is only
possible because we have written “export” in “Customer.ts” file. The import and export generate
code which follows CommonJs , AMD or UMD specifications. In case you are new to these
specifications please see this CommonJs video which explains the protocol in more detail.

import {Customer} from '../Model/Customer'

Let’s try to understand how “Customer”


component is located. If you see it’s using a
relative path. In the import it says
“../Model/Customer”.

The “../” says go one folder up. So we are


currently in the “Component” folder , so with
“../” it travels to the root and from that point it
makes entry in to the “Model” folder.

The next import command imports angular core components. In this we have not given any relative
path using “../” etc. So how does typescript locate the angular core components ?.

import {Component} from "@angular/core"

If you remember we had used node to load Angular and node loads the JS files in the
“node_modules” folder. So how does typescript compiler automatically knows that it has to load the
Angular components from “node_modules” folder.
Typescript compiler uses the configuration from “tsconfig.json” file. In the configuration we have
one property termed as “moduleResolution. It has two values:-

 Classic :- In this mode typescript relies on “./” and “../” to locate folders.
 Node :- In this mode typescript first tries to locate components in “node_modules” folder
and if not found then follows the “../” convention to traverse to the folders.

In our tsconfig.json we have defined the mode as “node” this makes typescript hunt modules
automatically in “node_modules” folder. That makes the “import” of Angular components work.
{
{
....
....
"moduleResolution": "node",
....
....
}
}

So now that both the import statements are applied let us create the “CustomerComponent” and
from that let’s expose “Customer” object to the UI with the object name “CurrentCustomer”.

export class CustomerComponent {


CurrentCustomer:Customer = new Customer();
}

As we said previously that component connects / binds the model to the HTML UI. So there should
be some code which tells that “CustomerComponent” is bounded with HTML UI. That’s done by
something termed as “Component MetaData Attribute”. A component metadata attribute starts
with “@Component” which has a “templateUrl” property which specifies the HTML UI with which
the component class is tied up with.

@Component({
selector: "customer-ui",
templateUrl: "../UI/Customer.html"
})

This attribute is then decorated on the top of the component. Below goes the full code.

@Component({
selector: "customer-ui",
templateUrl: "../UI/Customer.html"
})
export class CustomerComponent {
CurrentCustomer:Customer = new Customer();
}
Putting in simple words binding code is
nothing but a simple typescript class
which decorated by the “@Component”
attribute which dictates that this
typescript class is binded with which UI.

Below goes the full code of the Angular component.

// Import statements
import {Component} from "@angular/core"
import {Customer} from '../Model/Customer'

// Attribute metadata
@Component({
selector: "customer-ui",
templateUrl: "../UI/Customer.html"
})
// Customer component class exposing the customer model
export class CustomerComponent {
CurrentCustomer:Customer = new Customer();
}

Step 8:- Creating the Customer HTML UI – Directives and Interpolation

Now from the “CustomerComponent” , “Customer” is exposed via the “CurrentCustomer” object to
UI. So in the HTML UI we need to refer this object while binding.

In the HTML UI the object is binded by using “Directives”. Directives are tags which direct how to
bind with the UI.

For instance if we want to bind “CustomerName” with HTML textbox code goes something as shown
below:-

 “[(ngModel)]” is a directive which will help us send data from the object to UI and vice versa.
 Look at the way binding is applied to the object. It’s referring the property as
“CurrentCustomer.CustomerName” and not just “CustomerName”. Why ??. Because if you
remember the object exposed from the “CustomerComponent” is “CurrentCustomer”
object. So you need to qualify “CurrentCustomer.CustomerCode”.

<input type="text" [(ngModel)]="CurrentCustomer.CustomerName">


 Round brackets indicate data sent from UI to
object.
 Square brackets indicate data is sent from
object to UI.
 If both are present then it’s a two way binding.

There would be times when we would like to display object data on the browser. By using “{{“ braces
we can display object data with HTML tags. In the below HTML we are displaying “CustomerName”
mixed with HTML BR tag. These braces are termed as “INTERPOLATION”. If you see the dictionary
meaning of interpolation it means inserting something of different nature in to something else.

In the below code we are inserting object data within HTML.

{{CurrentCustomer.CustomerName}}<br />

Below goes the full HTML UI code with binding directives and interpolation.

<div>
Name:
<input type="text" [(ngModel)]="CurrentCustomer.CustomerName"><br /><br />
Code:
<input type="text" [(ngModel)]="CurrentCustomer.CustomerCode"><br /><br />
Amount:
<input type="text" [(ngModel)]="CurrentCustomer.CustomerAmount"><br /><br
/>
</div>
{{CurrentCustomer.CustomerName}}<br /><br />
{{CurrentCustomer.CustomerCode}}<br /><br />
{{CurrentCustomer.CustomerAmount}}<br /><br />

Step 9:- Creating the Module

Module is a container or you can say it’s a logical grouping of components and other services.

So the first import in this module is the “CustomerComponent” component.

import { CustomerComponent } from '../Component/CustomerComponent';

We also need to import “BrowserModule” and “FormsModule” from core angular.


“BrowserModule” has components by which we can write IF conditions and FOR loop.
“FormsModule” provides directive functionality like “ngModel”, expressions and so on.

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


import {FormsModule} from "@angular/forms"
We also need to create a typescript class “MainModuleLibrary”. At this moment this class does not
have any code but it can have code which will provide component level logic like caching ,
initialization code for those group of components and so on.

export class MainModuleLibrary { }

To create a module we need to use import “NgModule” from angular core. This helps us to define
module directives.

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

“NgModule” has three properties:-

 Imports: - If this module is utilizing other modules we define the modules in this section.
 Declarations: - In this section we define the components of the modules. For now we only
have one component ‘CustomerComponent”.
 Bootstrap: - This section defines the first component which will run. For example we can
have “HomeComponent”, “CustomerComponent” and so on. But the first component which
will run is the “HomeComponent” so that we need to define in this section.

@NgModule({
imports: [BrowserModule,
FormsModule],
declarations: [CustomerComponent],
bootstrap: [CustomerComponent]
})

Below goes the full code of Angular module which we discussed in this section.

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


import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from "@angular/forms"
import { CustomerComponent } from '../Component/CustomerComponent';

@NgModule({
imports: [BrowserModule,
FormsModule],
declarations: [CustomerComponent],
bootstrap: [CustomerComponent]
})
export class MainModuleLibrary { }
Step 10:- Creating the “Startup.ts” file

So we have created the UI, we have


created the models, we have created
components and these components are
grouped in to modules. In an angular
application you can have many
modules.

So you need to define the startup


module. So let’s create a “Startup.ts”
file which will define the startup
module.

Below goes the “Startup.ts” file in which we have defined which module will be bootstrapped.

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


import { MainModuleLibrary } from '../Module/MainModuleLibrary';
const platform = platformBrowserDynamic();
platform.bootstrapModule(MainModuleLibrary);

Step 11:- Invoking “Startup.ts” file using main angular page

So let us create a startup HTML page which will invoke the “Startup.ts”. Now in this page we will
need to import four JavaScript framework files Shim , Zone , Meta-data and System JS as shown in
the below code.

<script src="../../node_modules/core-js/client/shim.min.js"></script>
<script src="../../node_modules/zone.js/dist/zone.js"></script>
<script src="../../node_modules/reflect-metadata/Reflect.js"></script>
<script src="../../node_modules/systemjs/dist/system.src.js"></script>

Below are the use of JS files :-

Shim.min.js This framework ensures that ES 6 javascript can run in old browsers.
Zone.js This framework ensures us to treat group of Async activities as one zone.
Reflect.js Helps us to apply meta-data on Javascript classes. We are currently using
@NgModule and @NgComponent as attributes.
System.js This module will helps to load JS files using module protocols like
commonjs , AMD or UMD.

In this HTML page we will are calling the “systemjs.config.js” file. This file will tell system JS which
files to be loaded in the browser.

<script src="../systemjs.config.js"></script>
<script>
System.config({
"defaultJSExtensions": true
});

System.import('startup').catch(function (err) { console.error(err); });


</script>

In the “import” we need to specify “startup” which will invoke “startup.js” file.

System.import('startup').catch(function (err) { console.error(err); });

Our customer screen in with the name “Customer.html”. So to load in to this screen we need to
define a place holder. So in this place holder our Customer HTML page will load.

<customer-ui></customer-ui>

If you remember when we created the component class we had said to load the HTML page in a
selector. So that selector is nothing but a tag (placeholder) to load our Customer page.

@Component({
selector: "customer-ui",
templateUrl: "../UI/Customer.html"
})

Below goes the full HTML page with all scripts and the place holder tag.

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="../../node_modules/core-js/client/shim.min.js"></script>
<script src="../../node_modules/zone.js/dist/zone.js"></script>
<script src="../../node_modules/reflect-metadata/Reflect.js"></script>
<script src="../../node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="../systemjs.config.js"></script>
<script>
System.config({
"defaultJSExtensions": true
});

System.import('startup').catch(function (err) { console.error(err); });


</script>
<body>
<customer-ui></customer-ui>
</body>
</html>

Step 12:- Installing http-server and running the application

In order to run the application we need a web server. So go to integrated terminal and type “npm
install http-server”. “http-server” is a simple, zero-configuration command-line http server which we
can use for testing, local development and learning. For more details visit
https://www.npmjs.com/package/http-server

To run this server we need


to type “http” in the VS
code integrated terminal
as shown in the figure.

In case your 80 port is


blocked you can run this
server on a specific port
using “http-server –p 99”.
This will run this server
over 99 port.
So once the web server is running you
can now browse to the main angular
HTML page.
Main angular page means the page in
which we have put the scripts, put the
place holder , systemjs and so on.

Please note Customer.html is not the


main page. This page will be loaded in
the placeholder of main angular page.

Once the sites are running type in one


of the textboxes and see the
automation of binding output in
expression.

How to the run the source code?

The source code that is attached in this book is without “node_modules” folder. So to run the code
you need to open the folder using VS code and then do a NPM using the integrated terminal on the
folder where you have “package.json” file.

Lab 6:- Implementing SPA using Angular routing

Fundamental of Single page application

Now a days Single page application ( SPA) has become the style of creating websites. In SPA we load
only things which we need and nothing more than that.
At the right-hand side is a simple
website where we have Logo and
header at the top, Left menu links and
footer at the bottom.

So the first time when user comes to the


site all the sections of the master page
will be loaded.
But when user clicks on Supplier link
only Supplier page will load and not
logo, header and footer again. When
user clicks on Customer link only
Customer page will be loaded and not all
other sections.

Angular routing helps us to achieve the


same.

Step 1 :- Creating the Master Page

As everything revolves around the Master Page so the first logical step would be is to create the
“MasterPage”.

In this master page we will create placeholders for logo , header , menu , footer , copyright and so
on. These sections will be loaded only once when the user browses the website first time. And in the
later times only pages which are needed will be loaded on demand.

Below is the sample HTML code which has all the placeholder sections. You can also see in this code
we have kept a “DIV” tag section in which we would loading the pages on-demand.
Below is the overall main sections of “MasterPage”. Please note the “DIV” section with name
“dynamicscreen” where we intend to load screens dynamically. We will fill these sections later.

<table border="1">
<tr>
<td>Logo</td>
<td>Header</td>
</tr>
<tr>
<td>Left Menu</td>
<td>
<div id=”dynamicscreen”>
Dynamic screen will be loaded here
</div>
</td>
</tr>
<tr>
<td>Footer</td>
<td>Copyright</td>
</tr>
</table>

Step 2:- Creating the Supplier page and welcome page

Let’s create two more HTML UI one “Supplier” page and “Welcome” page.In both these HTML pages
we are not doing much , we have just greeting messages.
Below is the supplier pages text.

This is the Suppliers page

Below is welcome pages text.

Welcome to the website

Step 3:- Renaming placeholder in Index.html

As explained in Part 1 “Index.html” is the startup page and it bootstraps all other pages using
systemjs. In the previous lesson inside “Index.html” , “Customer.html” page was loading. But now
that we have master page so inside index page “MasterPage.html” will load.

So to make it more meaningful lets rename “customer-ui” tag to “main-ui”. In this “main-ui” section
we will load the master page and when end user clicks on the master page left menu links supplier ,
customer and welcome pages will load.

<body>
<main-ui></main-ui>
</body>

So if look at the flow , first index.html


will get loaded and then inside the
“main-ui” , “masterpage.html” gets
loaded.

Step 4:- Removing selector from CustomerComponent

Now the first page to load in the index.html will be Masterpage and not Customer page. So we need
to remove the selector from “CustomerComponent.ts”. This selector will be moved to masterpage
component in the later sections.
The final code of “CustomerComponent.ts” would look something as show below.

import {Component} from "@angular/core"


//importing the customer model
import {Customer} from '../Model/Customer'
@Component({
templateUrl: "../UI/Customer.html"
})
export class CustomerComponent {
//this is binding
CurrentCustomer:Customer = new Customer();

Step 5:- Creating Components for Master , Supplier and Welcome page

Every UI which is Angular enabled should have


component code file.
We have created 3 user interfaces so we need
three component code files for the same.

In the component folder, we will create three


component TS files “MasterPageComponent.ts”
, “SupplierComponent.ts” and
“WelcomeComponent.ts”.

You can visualize component code files as code


behind for Angular UI.
So first let’s start with “MasterPage.html” component which we have named as
“MasterPageComponent.ts”. This master page will get loaded in “Index.html” in the initial
bootstrapping process. You can see in this component we have put the selector and this will be the
only component which will have the selector.

import {Component} from "@angular/core"

@Component({
selector: "main-ui",
templateUrl: "../UI/MasterPage.html"
})
export class MasterPageComponent {
}

Below is the component code for “Supplier.html”.

import {Component} from "@angular/core"

@Component({

templateUrl: "../UI/Supplier.html"
})
export class SupplierComponent {
}

Below is the component code for “Welcome.html”. Both Supplier and Welcome component do not
have the selector , only the master page component has it as it will be the startup UI which will get
loadedin index page.

import {Component} from "@angular/core"

@Component({
templateUrl: "../UI/Welcome.html"
})
export class WelcomeComponent {
}

Step 6: - Creating the routing constant collection

Once the master page is loaded in the index page, end user will click on the master page links to
browse to supplier page, customer page and so on.Now in order that the user can browse properly
we need to define the navigation paths. These paths will be specified in the “href” tags in the later
steps.

When these paths will be browsed, it will invoke the components and components will load the UI.
Below is a simple table with three columns. The first column specifies the path pattern, second
which component will invoke when these paths are browsed and the final column specifies the UI
which will be loaded.

Path/URL Component UI which will be loaded


/ WelcomeComponent.ts Welcome.html
/Customer CustomerComponent.ts Customer.html
/Supplier SupplierComponent.ts Supplier.html

The paths and component entries needs to be defined in a simple literal collection as shown in the
below code. You can see the “ApplicationRoutes” is a simple collection where we have defined path
and the component which will be invoked. These entries are made as per the table specified at the
top.

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


import {CustomerComponent} from '../Component/CustomerComponent';
import {SupplierComponent} from "../Component/SupplierComponent";
import {WelcomeComponent} from "../Component/WelcomeComponent";

export const ApplicationRoutes = [


{ path: 'Customer', component: CustomerComponent },
{ path: 'Supplier', component: SupplierComponent },
{ path: '', component:WelcomeComponent }
];

As a good practice all the above code we have defined in a separate folder “routing” and in a
separate file “routing.ts”.
Step 7: - Defining routerLink and router-outlet

The navigation ( routes) defined in “Step 6” in the collection needs to referred when we try to
navigate inside the website. For example, in the master page we have defined the left menu
hyperlinks.

So rather than using the “href” tag of HTML we need to use “[routerLink]”.

<a href=”Supplier.html”>Supplier</a>

We need to use “[routerLink]” and the value of “[routerLink]” will be the path specified in the routes
collection define the previous step. For example in the “ApplicationRoutes” collection we have made
one entry for Supplier path we need to specify the path in the anchor tag as shown in the below
code.

<a [routerLink]="['Supplier']">Supplier</a>

When the end user clicks on the left master page links the pages (supplier page, customer page and
welcome page) will get loaded inside the “div” tag. For that we need to define “router-outlet”
placeholder. Inside this placeholder pages will load and unload dynamically.

<div id=”dynamicscreen”>
<router-outlet></router-outlet>
</div>

So if we update the master page defined in “Step 1” with “router-link” and “router-outlet” we would
end up with code something as shown below.

<table border="1">
<tr>
<td><img src="http://www.questpond.com/img/logo.jpg" alt="Alternate Text"
/>
</td>
<td>Header</td>
</tr>
<tr>
<td><u>Left Menu</u><br /><br /><br />
<a [routerLink]="['Supplier']">Supplier</a> <br /><br />
<a [routerLink]="['Customer']">Customer</a></td><td>
<div id=”dynamicscreen”>
<router-outlet></router-outlet>
</div>
</td>
</tr>
<tr>
<td>Footer</td>
<td></td>
</tr>
</table>

Step 8:- Loading the routing in Main modules

In order to enable routing collection paths defined in “ApplicationRoutes” we need to load that in
the “MainModuleLibrary” as shown in the below code. “RouterModule.forRoot” helps load the
application routes at the module level.

Once loaded at the module level it will be available to all the components for navigation purpose
which is loaded inside this module.

@NgModule({
imports: [RouterModule.forRoot(ApplicationRoutes),
BrowserModule,
FormsModule],
declarations:
[CustomerComponent,MasterPageComponent,SupplierComponent],
bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

The complete code with routes would look something as shown below.

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


import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from "@angular/forms"
import { CustomerComponent } from '../Component/CustomerComponent';
import { SupplierComponent } from '../Component/SupplierComponent';
import { MasterPageComponent } from '../Component/MasterPageComponent';
import { RouterModule } from '@angular/router';
import { ApplicationRoutes } from '../Routing/Routing';

@NgModule({
imports: [RouterModule.forRoot(ApplicationRoutes),
BrowserModule,
FormsModule],
declarations:
[CustomerComponent,MasterPageComponent,SupplierComponent],
bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

Step 9:- Seeing the output

Now run the website and try to browser to UI folder and you should see the below animated video
output. You can see that the logo gets loaded only once and later when the user is click on the
supplier links , customer links image is not loading again and again.
Step 10:- Fixing Cannot match any routes error

If you do a “f12” and check in the console part of the chrome browser , you would see the below
error. Can you guess what the error is ?.

Your current angular application is route


enabled. So every URL which is browsed
is looked up in to routes collection.
So the first URL which you browse is
“/UI” and it tries to lookup in to your
routes collection and does not find one.

So that’s why it throws up the above


error.

In order to fix the same make one more entry for “UI” path and point it to “WelcomeComponent”.

export const ApplicationRoutes = [


{ path: 'Customer', component: CustomerComponent },
{ path: 'Supplier', component: SupplierComponent },
{ path: '', component:WelcomeComponent },
{ path: 'UI', component:WelcomeComponent }

];

Understanding the flow

1. End user loads index.html page.


2. Index.html triggers systemjs and loads masterpage.html.
3. When end users click on masterpage links, other pages are loaded in “router-outlet”
placeholders.
Lab 7 :- Implementing validation using Angular form

In this lab we will try to understand how we can implement validations using Angular framework.

Requirement of a good validation structure

One of the important legs of software


application is validations.

Validations are normally applied to user


interfaces (Forms) and User interfaces have
controls and on the controls, we apply
validations.
In Angular form validation architecture
structure is as follows.

At the top we have FormGroup ,


FormGroup has FormControls and
FormControls has one or many validations.

There are 3 broader steps to implement Angular validation

1. Create FormGroup.
2. Create FormControl and with proper validations.
3. Map those validations to the HTML Form.

What kind of validation will we implement in this Lab ?

In this lab we will implement the following validation on our Customer screen: -

 Customer Name should be compulsory.


 Customer code should be compulsory.
 Customer code should be in the format of A1001, B4004 and so on. In other words the first
character should be an capital alphabet followed by 4 letter numeric.

Note :- Customer code has composite validations.

Where to put Validations ?

Before even we start with validations we need to decide which is the right place to put validations. If
you see in Angular we have three broader section UI , Component and Model. So let’s think over
which is the right layer to put validations.

 UI :- UI is all about look and feel and positioning of controls. So putting validation in this
layer is a bad idea. Yes on this layer we will apply validations but the validation code should
be in some other layer.
 Component :- Component is the code behind ( Binding code) which binds the UI and Model.
In this layer more binding related activity should be put. One component can use many
models so if we put the validation logic here we need to duplicate that in other components
as well.
 Model :- A Model represents a real world entity like person , user , admin , product etc.
Behavior a.k.a validations are part of the model. A model has Data and Behavior. So the right
place where validations should be present is this Layer.

So let us put validation as a part of the model.

Step 1 :- Import necessary components for Angular validators

So the first step is to import the necessary components for angular validators in the customer
model. All angular validator components are present in “@angular/forms” folder. We need to
import five components NgForm, FormGroup, FormControl and validators.

NgForm :- Angular tags for validation.


FormGroup :- Helps us to create collection of validation.
FormControl and Validators:- Helps us to create individual validation inside FormGroup.
FormBuilder :- Helps us to create the structure of Form group and Form controls. Please note one
Form group can have many FormControls.

import {NgForm,
FormGroup,
FormControl,
Validators,
FormBuilder } from '@angular/forms'

Step 2 :- Create FormGroup using FormBuilder

The first step is to create an object of FormGroup in which we will have collection of validation. The
FormGroup object will be constructed using the “FormBuilder” class.

formGroup: FormGroup = null; // Create object of FormGroup


var _builder = new FormBuilder();
this.formGroup = _builder.group({}); // Use the builder to create object

Step 3 :- Adding a simple validation


Once the FormGroup object is created the next step is to add controls in the FormGroup collection.
To add a control we need to use “addControl” method. The first parameter in “addControl” method
is the name of the validation and second is the Angular validator type to be added.

Below is a simple code in which we are adding a “CustomerNameControl” using the


“Validators.required” FormControl. Please note “CustomerNameControl” is not a reserved keyword.
It can be any name like “CustControl”.

this.formGroup.addControl('CustomerNameControl', new
FormControl('',Validators.required));

Step 4 :- Adding a composite validation

If you want to create a composite validation then you need to create a collection and add it using
“compose” method as shown in the below code.

var validationcollection = [];


validationcollection.push(Validators.required);
validationcollection.push(Validators.pattern("^[A-Z]{1,1}[0-9]{4,4}$"));
this.formGroup.addControl('CustomerCodeControl', new FormControl('',
Validators.compose(validationcollection)));

Full Model code with validation

Below is the full Customer Model code with all three validation as discussed in the previous section.
We have also commented the code so that you can follow it.

// import components from angular/form


import {NgForm,
FormGroup,
FormControl,
Validators,
FormBuilder } from '@angular/forms'
export class Customer {
CustomerName: string = "";
CustomerCode: string = "";
CustomerAmount: number = 0;
// create object of form group
formGroup: FormGroup = null;

constructor(){
// use the builder to create the
// the form object
var _builder = new FormBuilder();
this.formGroup = _builder.group({});

// Adding a simple validation


this.formGroup.addControl('CustomerNameControl', new
FormControl('',Validators.required));

// Adding a composite validation


var validationcollection = [];
validationcollection.push(Validators.required);
validationcollection.push(Validators.pattern("^[A-Z]{1,1}[0-
9]{4,4}$"));
this.formGroup.addControl('CustomerCodeControl', new
FormControl('', Validators.compose(validationcollection)));
}
}

Step 5 :- Apply formGroup to HTML form

The next thing is to apply ‘formGroup’ object to the HTML form. For that we need to use
“[formGroup]” angular tag in that we need to specify the “formGroup” object exposed via the
customer object.

<form [formGroup]="CurrentCustomer.formGroup">
</form>

Step 6:- Apply validations to HTML control

The next step is to apply formgroup validation to the HTML input controls. That’s done by using
“formControlName” angular attribute. In “formControlName” we need to provide the form control
name which we have created while creating the validation.

<input type="text" formControlName="CustomerNameControl"


[(ngModel)]="CurrentCustomer.CustomerName"><br /><br />

Step 7:- Check if Validations are ok


When user starts filling data and fulfilling the validations we would like to check if all validations are
fine and accordingly show error message or enable / disable UI controls.

In order to check if all validations are fine we need to use the “valid” property of “formGroup”.
Below is a simple example where the button will be disabled depending on whether validations are
valid or not. “[disabled]” is an angular attribute which enables and disables HTML controls.

<input type="button"
value="Click" [disabled]="!(CurrentCustomer.formGroup.valid)"/>

Step 8:- Checking individual validations

“CurrentCustomer.formGroup.valid” check all the validations of the “FormGroup” but what if we


want to check individual validation of a control.

For that we need to use “hasError” function.


“CurrentCustomer.formGroup.controls['CustomerNameControl'].hasError('required')” checks that
for “CustomerNameControl” has the “required” validation rule been fulfilled. Below is a simple code
where we are displaying error message in a “div” tag which visible and not visible depending on
whether the “hasError” function returns true or false.

Also note the “!” ( NOT) before “hasError” which says that if “hasError” is true then hidden should be
false and vice versa.

<div
[hidden]="!(CurrentCustomer.formGroup.controls['CustomerNameControl'].hasEr
ror('required'))">Customer name is required </div>

Step 9 :- standalone elements

In our forms we have three textboxes “CustomerName” , “CustomerCode” and “CustomerAmount”.


In these three textboxes only “CustomerName” and “CustomerCode” has validations while
“CustomerAmount” does not have validations.
Now this is bit funny but if we do not specify validations for a usercontrol which is inside a “form”
tag which has “formGroup” specified you would end up with a long exception as shown below.

Error: Uncaught (in promise): Error: Error in ../UI/Customer.html:15:0


caused by:
ngModel cannot be used to register form controls with a parent
formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:

<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({


firstName: new FormControl()
});

Or, if you'd like to avoid registering this form control, indicate


that it's standalone in ngModelOptions:

Example:

<div [formGroup]="myGroup">
<input formControlName="firstName">
<input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone:
true}">
</div>

Error:
ngModel cannot be used to register form controls with a parent
formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:

<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({


firstName: new FormControl()
});

Or, if you'd like to avoid registering this form control, indicate


that it's standalone in ngModelOptions:
Example:

<div [formGroup]="myGroup">
<input formControlName="firstName">
<input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone:
true}">
</div>

The above error can be simplified in three simple points : -

1. It says that you have enclosed a HTML control inside a HTML FORM tag which has Angular
form validations.
2. All controls specified inside HTML FORM tag which have angular validation applied SHOULD
HAVE VALIDATIONS.
3. If a HTML control inside Angular form validation does not have validation you can do one of
the below things to remove the exception: -
o You need to specify that it’s a standalone control.
o Move the control outside the HTML FORM tag.

Below is the code how to specify “standalone” for Angular validations.

<input type="text" [ngModelOptions]="{standalone:true}"


[(ngModel)]="CurrentCustomer.CustomerAmount"><br /><br />

Also talk about we can remove from the form control and what happens

Complete code of Customer UI with validations applied

Below is the complete Customer UI with all three validations applied to “CustomerName” and
“CustomerCode” controls.

<form [formGroup]="CurrentCustomer.formGroup">
<div>
Name:
<input type="text" formControlName="CustomerNameControl"
[(ngModel)]="CurrentCustomer.CustomerName"><br /><br />
<div
[hidden]="!(CurrentCustomer.formGroup.controls['CustomerNameControl'].hasEr
ror('required'))">Customer name is required </div>
Code:
<input type="text" formControlName="CustomerCodeControl"
[(ngModel)]="CurrentCustomer.CustomerCode"><br /><br />
<div
[hidden]="!(CurrentCustomer.formGroup.controls['CustomerCodeControl'].hasEr
ror('required'))">Customer code is required </div>
<div
[hidden]="!(CurrentCustomer.formGroup.controls['CustomerCodeControl'].hasEr
ror('pattern'))">Pattern not proper </div>

Amount:
<input type="text"
[(ngModel)]="CurrentCustomer.CustomerAmount"><br /><br />
</div>
{{CurrentCustomer.CustomerName}}<br /><br />
{{CurrentCustomer.CustomerCode}}<br /><br />
{{CurrentCustomer.CustomerAmount}}<br /><br />
<input type="button"
value="Click" [disabled]="!(CurrentCustomer.formGroup.valid)"/>
</form>

Write reactive forms

Run and see your validation in action

Once you are done you should be able to see the validation in action as shown in the below figure.

Dirty , pristine , touched and untouched

In this lab we covered “valid” and “hasError” property and function. “formGroup” also has lot of
other properties which you will need when you are working with validations. Below are some
important ones.
Property Explanation
dirty This property signals if Value has been modified.
pristine This property says if the field has changed or not.
touched When the lost focus for that control occurs.
untouched The field is not touched.

Lab 8 :- Making HTTP calls

Importance of server side interaction

HTML user interfaces are dead if there is no server side interaction. Normally in a web application
we would like to send the data entered by end user to the server. On server side we would have
some kind of service which can be created in technologies like Java , C# and so on. The server side
technology can save, edit or delete this data in a database.

In simple words we need to understand how to make HTTP calls from Angular code to a server side
technology.

Yes , this is a pure Angular book

I intend to keep this book as a pure Angular


book. So teaching server side technology like
ASP.NET MVC , Java services , PHP is out of
scope.

So the server side service would be FAKED


(Mocked) by using “Angular inmemory Webapi”.
Please note this is not a service which you will
use for production its only for test and
development purpose.

In case you want to learn ASP.NET MVC you can


start from this video
https://www.youtube.com/watch?v=Lp7nSImO5
vk

Step 1 :- Creating a fake server side service

Even though we have decided that we will not be creating a professional server side service using
ASP.NET , Java etc but we will still need one. So we will be using a fake service called as “Angular in-
memory web api”.
Already the “Angular inmemory web api” has been installed when we did npm. You can check your
“package.json” file for the entry of “angular inmemory web api”.

So let’s create a folder called as “Api” and in


that lets add “CustomerApi.ts” file and in this
file we will write code which will create a fake
customer service.

On this fake service we will make HTTP calls.

Below is a simple service created using “angular-in-memory” open source. In this service we have
loaded a simple “customers” collection with some sample customer records.

import { InMemoryDbService } from 'angular2-in-memory-web-api'


import {Customer} from "../Model/Customer"
export class CustomerApiService implements InMemoryDbService {
createDb() {
let customers =[
{ CustomerCode: '1001', CustomerName: 'Shiv' , CustomerAmount :100.23
},
{ CustomerCode: '1002', CustomerName: 'Shiv1' , CustomerAmount :1.23
},
{ CustomerCode: '1003', CustomerName: 'Shiv2' , CustomerAmount :10.23
},
{ CustomerCode: '1004', CustomerName: 'Shiv3' , CustomerAmount
:700.23 }
]
return {customers};
}
}
So now when angular makes HTTP call it
will hit this in-memory API.

So when you make a HTTP GET it will


return the above four records. When you
make a HTTP POST it will add the data to
the in-memory collection.

In other words we do not need to create


a professional server side service using
ASP.NET or Java service.

Step 2 :- Importing HTTP and WebAPI module in to main module

The next step is to import “HttpModule” from “angular/http” and in-memory API in to main
module. Remember module is collection of components. So the “MainModule” has
“CustomerComponent” , “SupplierComponent”, “MasterpageComponent” and
“WelcomeComponent”.

import { HttpModule} from '@angular/http';


import {CustomerApiService} from "../Api/CustomerApi"

Also in the “NgModule” attribute in imports we need to specify “HttpModule” and


“InMemoryWebApiModule”.

@NgModule({
imports: [….
InMemoryWebApiModule.forRoot(CustomerApiService),
…..,HttpModule],
declarations: […],
bootstrap: [….]
})
export class MainModuleLibrary { }

Where do we put the HTTP call ?

The next question comes which is the right place to put HTTP calls ?.
So if you see the normal architecture of
Angular it is as follows: -

 User interface is binded with the


Angular component using bindings
”[()]”.
 So once end user starts putting data in
the UI the model object (in our case
it’s the customer object) will be loaded
and sent to the Customer component.
 Now customer component has the
filled customer object. So the right
place to make HTTP call is in the
component.

Step 3 :- Importing HTTP in the Customer component

So let’s go ahead and import the Angular HTTP inside the Customer component.

import { Http, Response, Headers, RequestOptions } from '@angular/http';

We do not need to create object of HTTP using the new keyword, it will be dependency injected via
the constructor. So on the constructor component we have defined the object injection of HTTP.

constructor(public http:Http){
}

Step 4:- Creating header and request information

When we send HTTP request from


client to server or we get response,
header information is passed with the
request and response. In header
information we have things like
content types , status , user agent
and so on.

So to create a request we need to first create a header and using that header create a request. One
of the header information we need to provide is type of content we are sending to server is it XML ,
JSON etc.

Below is how to create a simple request using basic header information.

let headers = new Headers({'Content-Type': 'application/json'});


let options = new RequestOptions({ headers: headers });
Step 5 :- Making HTTP calls and observables

Angular HTTP uses something called as observables. So angular is an observer and it subscribes to
observable like HTTP response. In other words, its listening to data coming from the server.

So the below code says that we will be making a GET call to “api/customers” URL and when the data
comes we will send the successful data to the “Success” function and when error occurs we will get
it in “Error” function.

var observable = this.http.get("api/customers", options);


observable.subscribe(res => this.Success(res),
res => this.Error(res));
Below is the code of Error and Success function. In “Success” function we are converting the
response to JSON and assigning it to “Customers” collection which is in the component. If we have
error we are displaying it in the browser console.

Error(err) {
console.debug(err.json());
}
Success(res) {
this.Customers = res.json().data;
}

Step 6 :- Creating a simple post and get call

With all that wisdom we have gathered from Step 4 and Step 5 lets write down two functions one
which will display data and the other which will post data.

Below is a simple “Display” function which makes a HTTP GET call.

Display(){
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
var observable = this.http.get("api/customers", options);
observable.subscribe(res => this.Success(res),
res => this.Error(res));
}
As soon as the customer UI is loaded the customer component object will be created. So in the
constructor we have called the “Display” function to load the customers collection.

export class CustomerComponent {


// other code removed for clarity
constructor(public http:Http){
this.Display();
}
// other codes removed for clarity
}

Below is simple “Add” function which makes a POST call to the server. In http POST call code below
you can see customer object sent as the third parameter.After the “Add” call we have made call to
“Display” so that we can see the new data added on the server.

Add(){
let headers = new Headers({
'Content-Type': 'application/json'
});
var cust:any = {};
cust.CustomerCode = this.CurrentCustomer.CustomerCode;
cust.CustomerName = this.CurrentCustomer.CustomerName;
cust.CustomerAmount = this.CurrentCustomer.CustomerAmount;
let options = new RequestOptions({ headers: headers });
var observable = this.http.post("api/customers",cust, options);
observable.subscribe(res => this.Success1(res),
res => this.Error(res));
this.Display();
}

In the above “Add” function you can see the below code which creates a fresh light weight customer
object. So why do we need to create this fresh new object ?.

var cust:any = {};


cust.CustomerCode = this.CurrentCustomer.CustomerCode;
cust.CustomerName = this.CurrentCustomer.CustomerName;
cust.CustomerAmount = this.CurrentCustomer.CustomerAmount;
The current customer object has lot of
other things like validations , prototype
object etc. So posting this whole object
to the server does not make sense. We
just want to send three properties
“CustomerCode”, “CustomerAmount”
and “CustomerName”.

In other words we need to create a light


weight DTO ( Data transfer object ) which
just has those properties.

Step 7 :- Connecting components to User interface

Now that our component is completed we need to attach the “Add” function to the button using
the “click” event of Angular. You can see that the (click) is inside a round bracket , in other words we
are sending something(event click) from UI to the Object.

<input type="button"
value="Click" (click)="Add()"
[disabled]="!(CurrentCustomer.formGroup.valid)"/>

Also we need to create a table in which we will use “ngFor” loop and display the customers
collection on the HTML UI. In the below code we have created a temporary object “cust” which
loops through the “Customers” collection and inside <td> tag we are using the expressions
({{cust.CustomerName}}) to display data.

<table>
<tr>
<td>Name</td>
<td>code</td>
<td>amount</td>
</tr>
<tr *ngFor="let cust of Customers">
<td>{{cust.CustomerName}}</td>
<td>{{cust.CustomerCode}}</td>
<td>{{cust.CustomerAmount}}</td>
</tr>
</table>

Go ahead and run the application. If you go and add “customer” object you should see the HTTP calls
happening and the list getting loaded in the HTML table.
Lab 9:- Input, Output and emitters

Theory

Reusability is one of the most important


aspects of development. As Angular is a UI
technology we would like to create UI controls
and reuse them in different UI.

For example in the Customer UI we have the


table grid display. If we want to create grid in
other UI we need to again repeat the
“<tr><td>” loop. It would be great if we can
create a generic reusable grid control which
can be plugged in to any UI.

If we want to create a GENERIC reusable


grid control you need to think
GENERICALLY, you need to think in terms
of INPUTS and OUTPUTS.

So the first visualization which you should


have in your mind is that your GRID
control is like a self-contained unit which
gets a input of some data collection and
when any one selects grid data the
selected object is sent outside.

So if you are using this grid control with a


Customer UI you get a Customer
collection , if you are using a Supplier UI
you will get a supplier collection.

In order to achieve this generic thought process Angular


has provided three things Input , Output and Event
emitters.

Input helps us define the input data to the user control.


Output uses event emitters to send data to the UI in
which the user control is located.
Planning how the component will look like

First let us plan how our grid component will look like. Grid component will be called in main HTML
using “<grid-ui></grid-ui>” HTML element. The grid component will have three attributes: -

 grid-columns:- This will be a input in which we will specify the columns names of the grid.
 grid-data :- This will be again a input in which we will provide the data to be displayed on the
grid.
 grid-selected :- This will be a output from which the selected object will be sent via emitter
events to the contained UI.

<grid-ui [grid-columns]=”In this we will give column names"


[grid-data]="In this we will give data for grid"
(grid-selected)="The selected object will be sent in event">
</grid-ui>

Step 1 :- Import input , output and Event Emitter

So first let us go ahead and add a separate file


for grid component code and name it
“GridComponent.ts”.

In this file, we will write all code that we need


for Grid component.

The first step is to add necessary components which will bring in Input and Output capabilities. For
that we need to import component , Input , Output and event emitter component from
“angular/core”.

import {Component,
Input,
Output,
EventEmitter} from "@angular/core"

Step 2 :- Creating the reusable GridComponent class

As this is a component we need to decorate the class with “@Component” decorator. The UI for this
component will coded in “Grid.html”. You can also see in the below code we defined the selector
has “grid-ui” , can you guess why ?.
If you remember in the planning phase we had said that the grid can be called by using “<grid-ui>”
tag.

@Component({
selector: "grid-ui",
templateUrl : "../UI/Grid.html"
})
export class GridComponent {
}

Step 3 :- Defining inputs and output

As this is a grid component we need data for the grid and column names for the grid. So we have
created two array collection one, “gridColumns” (which will have column names) and “gridData” ( to
data for the table).

export class GridComponent {


// This will have columns
gridColumns: Array<Object> = new Array<Object>();
// This will have data
gridData: Array<Object> = new Array<Object>();
}

There are two methods “setGridColumns” and “setGridDataSet” which will help us to set column
names and table data to the above defined two variables.

These methods will be decorated by using “@Input” decorators and in this we will put the names by
which these inputs will be invoked while invoking this component.

// The top decorator and import code is removed


// for clarity purpose

export class GridComponent {


// code removed for clarity
@Input("grid-columns")
set setgridColumns(_gridColumns: Array<Object>) {
this.gridColumns = _gridColumns;
}
@Input("grid-data")
set setgridDataSet(_gridData: Array<Object>) {
this.gridData = _gridData;
}
}

The names defined in the input decorator will be used as shown below while making call to the
component in the main UI.

<grid-ui [grid-columns]=”In this we will give column names"


[grid-data]="In this we will give data for grid" >
</grid-ui>

Step 4 :- Defining Event emitters

As discussed in this Labs theory section we will have inputs and outputs. Outputs are again defined
by using “@Output” decorator and data is sent via event emitter object.

To define output we need to use “@Output” decorator as shown in the below code. This decorator
is defined over “EventEmitter” object type. You can see that the type is “Object” and not “Customer”
or “Supplier” because we want it to be of a generic type. So that we can attach this output with any
component type.

@Output("grid-selected")
selected: EventEmitter<Object> = new EventEmitter<Object>();

Now when any end user selects a object from the grid we need to raise event by using the
“EventEmitter” object by calling the “emit” method as shown below.

// Other codes have been removed for clarity purpose.


export class GridComponent {
@Output("grid-selected")
selected: EventEmitter<Object> = new EventEmitter<Object>();

Select(_selected: Object) {
this.selected.emit(_selected);
}
}

Below goes the full code of “GridComponent.ts” which we have discussed till now.

import {Component,
Input,
Output,
EventEmitter} from "@angular/core"

@Component({
selector: "grid-ui",
templateUrl : "../UI/Grid.html"
})
export class GridComponent {
gridColumns: Array<Object> = new Array<Object>();
// inputs
gridData: Array<Object> = new Array<Object>();

@Output("grid-selected")
selected: EventEmitter<Object> = new EventEmitter<Object>();
@Input("grid-columns")
set setgridColumns(_gridColumns: Array<Object>) {
this.gridColumns = _gridColumns;
}

@Input("grid-data")
set setgridDataSet(_gridData: Array<Object>) {
this.gridData = _gridData;
}

Select(_selected: Object) {
this.selected.emit(_selected);
}
}

Step 5 :- Creating UI for the reusable component

Also we need to create UI for the


“GridComponent.ts”. Remember if we have an
Angular component we NEED A HTML UI for it.

So in the UI folder we will add “Grid.html” in


which we will write the code of table display.
In the “GridComponent.ts” ( refer Step 4 of this Lab) we have defined input “gridColumns” variable
in which we will provide the columns for the grid. So for that we had made a loop using “*ngFor”
which will create the columns “<td>” dynamically.

<table>
<tr>
<td *ngFor="let col of gridColumns">
{{col.colName}}
</td>
</tr>
</table>

And to display data in the grid we need to loop through “gridData” variable.

<tr *ngFor="let colObj of gridData">


<td *ngFor="let col of gridColumns">
{{colObj[col.colName]}}
</td>
<td><a [routerLink]="['Customer/Add']"
(click)="Select(colObj)">Select</a></td>
</tr>

So the complete code of “Grid.html” looks as shown below.

<table>
<tr>
<td *ngFor="let col of gridColumns">
{{col.colName}}
</td>
</tr>
<tr *ngFor="let colObj of gridData">
<td *ngFor="let col of gridColumns">
{{colObj[col.colName]}}
</td>
<td><a [routerLink]="['Customer/Add']"
(click)="Select(colObj)">Select</a></td>
</tr>
</table>
Step 6 :- Consuming the component in the customer UI

So now that our reusable component and its UI is completed l, lets call the component in the
“Customer.html” UI.

Below is the full proper code which has column names defined in “grid-columns” and in “grid-data”
we have set “Customers” collection. This “Customers” collection object is exposed from the
“CustomerComponent” class. This “Customers” collection is that collection which we had created
during the “HTTP” call lab. This variable has collection of “Customer” data.

<grid-ui
[grid-
columns]="[{'colName':'CustomerCode'},{'colName':'CustomerName'},{'colName'
:'CustomerAmount'}]"
[grid-data]="Customers"
(grid-selected)="Select($event)"></grid-ui>

Also we need to ensure that the old “<table>” code is deleted and is replaced with the above “<grid-
ui>” input /output tag.

Step 7 :- Creating events in the main Customer component

If you remember in our “GridComponent”


we are emitting event by calling “emit”
method. Below is the code snippet for it.
Now this event which is emitted needs to
caught in the “CustomerComponent” and
processed.

export class GridComponent {


Select(_selected: Object) {
this.selected.emit(_selected);
}
}

So in order to catch that event in the main component we need to create a method in
“CustomerComponent” file. So in the customer component typescript file we will create a “Select”
function in which the selected customer will come from the GridComponent and that selected object
will be set to “CurrentCustomer” object.

export class CustomerComponent {


Select(_selected:Customer) {
this.CurrentCustomer.CustomerAmount =_selected.CustomerAmount;
this.CurrentCustomer.CustomerCode = _selected.CustomerCode;
this.CurrentCustomer.CustomerName = _selected.CustomerName;
}
}

Step 8 :- Defining the component in the mainmodule

Also we need to ensure that the “GridComponent” is loaded in the main module. So in the main
module import the “GridComponent” and include the same in the declaration of “NgModule”
decorator as shown in the below code.

import { GridComponent } from '../Component/GridComponent';


@NgModule({
imports: [RouterModule.forRoot(ApplicationRoutes),
InMemoryWebApiModule.forRoot(CustomerApiService),
BrowserModule,ReactiveFormsModule,
FormsModule,HttpModule],
declarations: [CustomerComponent,
MasterPageComponent,
SupplierComponent,
WelcomeComponent,
GridComponent],
bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

And that’s it hit Control + B , run the server and see your reusable grid working.

Lab 10:- Lazy loading using dynamic routes

Theory

Big projects will have lot of components and modules, in other words we will end up with lot of JS
files on the browser client side. Loading these JS files in ONE GO at the client browser side would
really hit performance.
If you load the current application
at this stage and see the developer
tools you will see on the network
tab all JS files are getting loaded at
the start.

When the first time the user


comes to the site we would like to
just load the welcome component
and master component JS only.

When the user clicks on supplier


and customer respective JS files
should be loaded at that moment.

Let’s investigate who is the culprit ?.

If you see the current architecture of our


project we have one module(MainModule.ts)
and all components current belong to this only
ONE Module. So when this module loads it
loads all components inside it.

In simple words we need to BREAK MODULES in


to separate physical module files.

Step 1 :- Creating three different physical modules

So as discussed in the previous part of the theory we need to first divide our project in to three
different physical module files: - MainModule , SupplierModule and CustomerModule.
So in the module folder lets create three different
physical module files. We already have
MainModule.ts we need to create two more.

MainModule.ts :- This module will load


“MasterPageComponent.ts” and
“WelcomeComponent.ts”.

SupplierModule.ts :- This module will load


“SupplierComponent.ts”.

CustomerModule.ts :- This will load


CustomerComponent and GridComponent.
Remember grid is used only in Customer UI so
this should load only when Customer
functionality is loaded.

Step 2 :- Removing Supplier and Customercomponent from MainModule

The first thing is we need to remove all references of CustomerComponent,SupplierComponent and


GridComponent from the MainModule. Below is the striked out source code which needs to be
removed from the MainModule. In the main module, we only have reference to
WelcomeComponent and MastePageComponent.

Two modules are decoupled from each other when import does not exist between those
modules. Even if you do not use the component and there is an import decoupling is not complete
and the JS will be loaded.

Lot of Code has been removed for clarity. Please download source code
for full code.
import { CustomerComponent } from '../Component/CustomerComponent';
import { SupplierComponent } from '../Component/SupplierComponent';
import { WelcomeComponent } from '../Component/WelcomeComponent';
import { GridComponent } from '../Component/GridComponent';
import { MasterPageComponent } from '../Component/MasterPageComponent';

@NgModule({
imports: [RouterModule.forRoot(ApplicationRoutes),
InMemoryWebApiModule.forRoot(CustomerApiService),
BrowserModule,ReactiveFormsModule,
FormsModule,HttpModule],
declarations: [CustomerComponent,
MasterPageComponent,
SupplierComponent,
WelcomeComponent,
GridComponent],
bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

Step 3 :- Creating different Route files

As said previously “A SIMPLE IMPORT


REFERENCE” will make two modules
coupled. If the modules are coupled those JS
files will be loaded.

If you remember “MainModule.ts” loads the


Routes from “Routing.ts” and Routing.ts has
import references to SupplierComponent
and CustomerComponent.

So loading routing will load the other


components as well and we will not be able
to achieve lazy loading.

So let us remove all references of Customer


and Supplier component from
MainModule.ts , see the striked out code
down below.

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


import {CustomerComponent} from '../Component/CustomerComponent';
import {SupplierComponent} from "../Component/SupplierComponent";
import {WelcomeComponent} from "../Component/WelcomeComponent";
export const ApplicationRoutes = [
{ path: 'Customer', component: CustomerComponent },
{ path: 'Supplier', component: SupplierComponent },
{ path: '', component:WelcomeComponent },
{ path: 'UI/Index.html', component:WelcomeComponent }
];

But still we need to still define routes for “Customer” and “Supplier” and the same time not use
“import” statement as that makes the module coupled. If you look at the current syntax of defining
route we need to have that component in the import or else we cannot define the route.

{ path: 'CustomerComponent', component:CustomerComponent },

For that Angular has given a nice property called as “loadChildren”. In “loadChildren” we need to
give the module in a single quote like a string. Which means that this thing will be evaluated during
run time and now compile time.

{
path: 'Customer',
loadChildren:'../Module/CustomerModuleLibrary#CustomerModuleLibrary'
}
The structure of “loadChildren” should follow this pattern: -

 The first element in the ‘loadChildren” is the folder name, in case module file is in a folder.
 The second element is the physical filename of the module. In our case the we have
“CustomerModuleLibrary.ts” , “SupplierModuleLibrary.ts” and so on.
 The third element after the “#” is the class name which should be loaded from the physical
module file. It’s very much possible you can have many classes in one physical module file ,
but after the “#” we define which of those classes should be loaded.

The full code of the route will look something as shown below.

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


import {WelcomeComponent} from "../Component/WelcomeComponent";
export const ApplicationRoutes = [
{ path: 'Customer',
loadChildren:'../Module/CustomerModuleLibrary#CustomerModuleLibrary' },
{ path: 'Supplier',
loadChildren: '../Module/SupplierModuleLibrary#SupplierModuleLibrary' },
{ path: '', component:WelcomeComponent },
{ path: 'UI/Index.html', component:WelcomeComponent },
{ path: 'UI', component:WelcomeComponent }
];

We also need to create two more route files one for “Customer” and one for “Supplier” as shown
below.

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


import {CustomerComponent} from "../Component/CustomerComponent";
export const CustomerRoutes = [
{ path: 'Add', component:CustomerComponent }
];

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


import {SupplierComponent} from "../Component/SupplierComponent";
export const SupplierRoutes = [
{ path: 'Add', component:SupplierComponent }
];

“SupplierRoutes” and “CustomerRoutes” are child routes while the “ApplicationRoutes” is the parent
route.

Step 4 :- Calling Child routes in Supplier and Customer modules

In supplier module and customer modules we need to load their respective routes defined in “Step
3”. To load child routes we need to use “RouterModule.forChild”.

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


import { CommonModule } from '@angular/common';
import {FormsModule , ReactiveFormsModule} from "@angular/forms"
import { SupplierComponent } from '../Component/SupplierComponent';
import { RouterModule } from '@angular/router';
import { SupplierRoutes } from '../Routing/SupplierRouting';
import {CustomerApiService} from "../Api/CustomerApi"
@NgModule({
imports: [RouterModule.forChild(SupplierRoutes),
CommonModule,ReactiveFormsModule,
FormsModule],
declarations: [SupplierComponent],
bootstrap: [SupplierComponent]
})
export class SupplierModuleLibrary { }

Same way we need to for Customer Module.

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


import { CommonModule } from '@angular/common';
import {FormsModule , ReactiveFormsModule} from "@angular/forms"
import { CustomerComponent } from '../Component/CustomerComponent';
import { GridComponent } from '../Component/GridComponent';
import { RouterModule } from '@angular/router';
import { CustomerRoutes } from '../Routing/CustomerRouting';
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
import {CustomerApiService} from "../Api/CustomerApi"
import { HttpModule } from '@angular/http';

@NgModule({
imports: [RouterModule.forChild(CustomerRoutes),
InMemoryWebApiModule.forRoot(CustomerApiService),
CommonModule,ReactiveFormsModule,
FormsModule,HttpModule],
declarations: [CustomerComponent,
GridComponent],
bootstrap: [CustomerComponent]
})
export class CustomerModuleLibrary { }

Step 5 :- Configuring routerlinks

In step 3 and 4 we have defined parent routes


and child routes. Parent routes are defined in
“Routing.ts” while child routes are defined in
“CustomerRouting.ts” and “SupplierRouting.ts”.
So now the router link has to be changed to
“Supplier/Add” and “Customer/Add” as shown
in the below code.

<a [routerLink]="['Supplier/Add']">Supplier</a> <br />


<a [routerLink]="['Customer/Add']">Customer</a><br>

So now the full code look of master page looks as shown below.

<table border="0" width="100%">


<tr>
<td width="20%"><img src="http://www.questpond.com/img/logo.jpg"
alt="Alternate Text" />
</td>
<td width="80%">Questpond.com Private limited</td>
</tr>
<tr>
<td valign=top><u>Left Menu</u><br />
<a [routerLink]="['Supplier/Add']">Supplier</a> <br />
<a [routerLink]="['Customer/Add']">Customer</a><br>
<a [routerLink]="['']">Home</a>
</td>
<td>
<div id=”dynamicscreen”>
<router-outlet></router-outlet>
</div>
</td>
</tr>
<tr>
<td></td>
<td>Copy right @Questpond</td>
</tr>
</table>

Step 6 :- Replacing browser module with common module

“BrowserModule” and “CommonModule” are modules of angular. “BrowserModule” has code


which starts up services and launches the application while “CommonModule” has directives like
“NgIf” and “NgFor”.
“BrowserModule” re-exports “CommonModule”. Or if I put in simple words “BrowserModule” uses
“CommonModule”. So if you are loading “BrowserModule” you are loading “CommonModule” also.
So now if you are loading “BrowserModule”
in all three modules then you will end
uploading “CommonModule” 3 times. When
you are doing Lazy Loading you really do not
want to load things 3 times , it should be
loaded only once.

So if you have “BrowserModule” in all three


modules then you would end up getting such
kind of error as shown in below figure.

This error says “BrowserModule” has already


been loaded in the “MainModule” please use
“CommonModule” in “CustomerModule” and
“SupplierModule”.

So in main module load the browser module and in rest of modules load “CommonModule”.

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


// Other imports have been removed for clarity
@NgModule({
imports: [RouterModule.forRoot(ApplicationRoutes),
InMemoryWebApiModule.forRoot(CustomerApiService),
BrowserModule,ReactiveFormsModule,
FormsModule,HttpModule],
declarations: [
MasterPageComponent,
WelcomeComponent],
bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }

But in customer and supplier module just load common module.

import { CommonModule } from '@angular/common';


// other imports has been removed for clarity

@NgModule({
imports: [RouterModule.forChild(SupplierRoutes),
CommonModule,ReactiveFormsModule,
FormsModule],
declarations: [SupplierComponent],
bootstrap: [SupplierComponent]
})
export class SupplierModuleLibrary { }

import { CommonModule } from '@angular/common';


// Other import has been removed for claroty
@NgModule({
imports: [RouterModule.forChild(CustomerRoutes),
InMemoryWebApiModule.forRoot(CustomerApiService),
CommonModule,ReactiveFormsModule,
FormsModule,HttpModule],
declarations: [CustomerComponent,
GridComponent],
bootstrap: [CustomerComponent]
})
export class CustomerModuleLibrary { }

Step 7 :- Check if Lazy loading is working

Now run your application , go to network tab and check if lazy loading is working. You can see when
the application run at the start only “WelcomeComponent” and “MasterPageComponent” is loaded.
Once you click on supplier and customer the respective components will loaded at that time.

Please put a proper filter so that you do not see all JS files in your network.
Acronym used in this book

 NPM :- Node package manager.


 TS :- TypeScript.
 JS :- Javascript.
 VS :- Visual studio.
 VS Code :- Visual studio code.
 WP :- Webpack
 OS :- Operating system.
 SPA :- Single page application.

You might also like