Learn Angular Step by Step: (Covering Angular 2 and Angular 4)
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.
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]
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.
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.
“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.
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.
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.
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.
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.
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"
}
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.
Angular is created using typescript language. So if you are doing development with Angular
typescript is the way to go ahead.
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.
Please do watch this 1 hour Training video on TypeScript which explains Typescript in more detail.
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.
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.
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.
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.
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.
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
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
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.
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.
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.
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.
Now in the “Customer.ts” we use “import” to call the exported class from the “Dal.ts”.
}
}
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.
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.
Below is the code for “Customer.js” which uses “require” to load “Dal.js”.
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.
In “ES6” module format to expose the class we need to “export” keywords and to consume we need
to use “import”.
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”.
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.
Lets demonstrate a module using “SystemJS”. So first goto Node command prompt and install
“systemjs”.
<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"
}
}
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);
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"
}
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:-
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:-
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.
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.
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.
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 ?.
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”.
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.
// 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();
}
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”.
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.
{{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 />
Module is a container or you can say it’s a logical grouping of components and other services.
To create a module we need to use import “NgModule” from angular core. This helps us to define
module directives.
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.
@NgModule({
imports: [BrowserModule,
FormsModule],
declarations: [CustomerComponent],
bootstrap: [CustomerComponent]
})
export class MainModuleLibrary { }
Step 10:- Creating the “Startup.ts” file
Below goes the “Startup.ts” file in which we have defined which module will be bootstrapped.
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>
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
});
In the “import” we need to specify “startup” which will invoke “startup.js” file.
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
});
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
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.
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.
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>
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.
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>
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.
Step 5:- Creating Components for Master , Supplier and Welcome page
@Component({
selector: "main-ui",
templateUrl: "../UI/MasterPage.html"
})
export class MasterPageComponent {
}
@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.
@Component({
templateUrl: "../UI/Welcome.html"
})
export class WelcomeComponent {
}
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.
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.
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>
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.
@NgModule({
imports: [RouterModule.forRoot(ApplicationRoutes),
BrowserModule,
FormsModule],
declarations:
[CustomerComponent,MasterPageComponent,SupplierComponent],
bootstrap: [MasterPageComponent]
})
export class MainModuleLibrary { }
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 ?.
In order to fix the same make one more entry for “UI” path and point it to “WelcomeComponent”.
];
In this lab we will try to understand how we can implement validations using Angular framework.
1. Create FormGroup.
2. Create FormControl and with proper validations.
3. Map those validations to the HTML Form.
In this lab we will implement the following validation on our Customer screen: -
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 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.
import {NgForm,
FormGroup,
FormControl,
Validators,
FormBuilder } from '@angular/forms'
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.
this.formGroup.addControl('CustomerNameControl', new
FormControl('',Validators.required));
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.
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.
constructor(){
// use the builder to create the
// the form object
var _builder = new FormBuilder();
this.formGroup = _builder.group({});
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>
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.
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)"/>
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>
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
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:
<div [formGroup]="myGroup">
<input formControlName="firstName">
<input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone:
true}">
</div>
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.
Also talk about we can remove from the form control and what happens
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>
Once you are done you should be able to see the validation in action as shown in the below figure.
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.
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.
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”.
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.
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”.
@NgModule({
imports: [….
InMemoryWebApiModule.forRoot(CustomerApiService),
…..,HttpModule],
declarations: […],
bootstrap: [….]
})
export class MainModuleLibrary { }
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: -
So let’s go ahead and import the Angular HTTP inside the Customer component.
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){
}
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.
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.
Error(err) {
console.debug(err.json());
}
Success(res) {
this.Customers = res.json().data;
}
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.
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.
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 ?.
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
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.
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"
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 {
}
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).
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 names defined in the input decorator will be used as shown below while making call to the
component in the main UI.
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.
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);
}
}
<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.
<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.
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.
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.
And that’s it hit Control + B , run the server and see your reusable grid working.
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.
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.
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 { }
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.
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.
We also need to create two more route files one for “Customer” and one for “Supplier” as shown
below.
“SupplierRoutes” and “CustomerRoutes” are child routes while the “ApplicationRoutes” is the parent
route.
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”.
@NgModule({
imports: [RouterModule.forChild(CustomerRoutes),
InMemoryWebApiModule.forRoot(CustomerApiService),
CommonModule,ReactiveFormsModule,
FormsModule,HttpModule],
declarations: [CustomerComponent,
GridComponent],
bootstrap: [CustomerComponent]
})
export class CustomerModuleLibrary { }
So now the full code look of master page looks as shown below.
So in main module load the browser module and in rest of modules load “CommonModule”.
@NgModule({
imports: [RouterModule.forChild(SupplierRoutes),
CommonModule,ReactiveFormsModule,
FormsModule],
declarations: [SupplierComponent],
bootstrap: [SupplierComponent]
})
export class SupplierModuleLibrary { }
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