Learn Angular
Learn Angular
Table of Contents
Introduction ............................................................................................................................................ 5
Who wrote this book? ............................................................................................................................ 6
How does this book teach you Angular ?................................................................................................ 6
Why do we need Angular ? ..................................................................................................................... 8
Lab 1:- Practicing NodeJS ...................................................................................................................... 10
Theory :- What is NodeJS ? ............................................................................................................... 10
Step 1 :- Installing NodeJs ................................................................................................................. 10
Step 2:- Practicing NPM Install command......................................................................................... 11
Step 3:- Understanding package.json file ......................................................................................... 11
Understanding versioning system in package.json ........................................................................... 13
What is package-lock.json file ? ..................................................................................................... 14
Important NPM commands .............................................................................................................. 14
Lab 2:- Practicing TypeScript ................................................................................................................. 15
Introduction :- Why do we need typescript ? ................................................................................... 15
Step 1 :- Installing typescript ............................................................................................................ 16
Step 2 :- Compiling a simple Typescript to Javascript ....................................................................... 16
Step 3 :- Using tsconfig.json file ....................................................................................................... 17
Lab 3:- Practicing VS Code..................................................................................................................... 18
What is VS Code? .............................................................................................................................. 18
Point number 1 :- All actions happens in a folder ............................................................................ 18
Point number 2 :- Creating files and folders ..................................................................................... 19
Point number 3 :- Explorer and Open Editors ................................................................................... 19
Point number 4:- Reveal in explorer ................................................................................................. 20
Point number 5: - Integrated terminal.............................................................................................. 20
Point number 6: - Running multiple terminals ................................................................................. 21
Point number 7: - Changing to soothing color themes ..................................................................... 21
Point number 8: - VS code settings ................................................................................................... 22
Lab 4:- Understanding Module loaders using SystemJs ....................................................................... 23
Step 1 :- TypeScript Modules and Import / Export keywords .......................................................... 24
Step 2 :- Module formats in JavaScript CommonJS , AMD , ES6 ....................................................... 25
Step 3 :- Calling Javascript module loaders in HTML UI .................................................................... 28
Lab 5:- Understanding Module Bundlers using WebPack .................................................................... 30
Introduction :- Runtime vs Compile time – Webpack Module bundler............................................ 30
Step 1 :- Install WebPack .................................................................................................................. 31
Step 2 :- Generate a Single Bundle ................................................................................................... 31
Step 3 :- Calling the javascript class in the webpage. ....................................................................... 31
Lab 6:- Components and Modules ( Running your first Angular Application) ...................................... 32
Introduction ...................................................................................................................................... 32
Step 1:- NPM install to get Angular framework ................................................................................ 32
Common errors during NPM install .................................................................................................. 35
Step 2:- Typescript configuration tsconfig.json ................................................................................ 36
Step 3:- Configuring SystemJS module loader .................................................................................. 37
Understanding Angular Component and module architecture ........................................................ 39
Step 4:- Following MVW Step by Step – Creating the folders .......................................................... 39
Step 5:- Creating the model .............................................................................................................. 41
Step 6:- Creating the Component ..................................................................................................... 42
Step 7:- Creating the Customer HTML UI – Directives and Interpolation ......................................... 45
Step 8:- Creating the Module............................................................................................................ 46
Step 9:- Creating the “Startup.ts” file ............................................................................................... 47
Step 10:- Invoking “Startup.ts” file using main angular page ........................................................... 48
Step 11:- Setting up the typescript compiler .................................................................................... 50
Step 12:- Running the http-server .................................................................................................... 50
How to the run the source code? ..................................................................................................... 51
Lab 7:- Implementing SPA using Angular routing ................................................................................. 52
Fundamental of Single page application ........................................................................................... 52
Step 1 :- Creating the Master Page ................................................................................................... 52
Step 2:- Creating the Supplier page and welcome page .................................................................. 54
Step 3:- Renaming placeholder in Index.html................................................................................... 54
Step 4:- Removing selector from CustomerComponent................................................................... 54
Step 5:- Creating Components for Master , Supplier and Welcome page ........................................ 55
Step 6: - Creating the routing constant collection ............................................................................ 56
Step 7: - Defining routerLink and router-outlet ................................................................................ 58
Step 8:- Loading the routing in Main modules ................................................................................. 59
Step 9:- Define APP BASE HREF ......................................................................................................... 60
Step 10:- Seeing the output .............................................................................................................. 61
Step 11:- Fixing Cannot match any routes error ............................................................................... 61
Understanding the flow .................................................................................................................... 62
Lab 8:- Implementing validation using Angular form ........................................................................... 63
Requirement of a good validation structure .................................................................................... 63
There are 3 broader steps to implement Angular validation ........................................................... 64
What kind of validation will we implement in this Lab ? .................................................................. 64
Where to put Validations ? ............................................................................................................... 64
Step 1 :- Import necessary components for Angular validators ....................................................... 65
Step 2 :- Create FormGroup using FormBuilder ............................................................................... 65
Step 3 :- Adding a simple validation.................................................................................................. 65
Step 4 :- Adding a composite validation ........................................................................................... 66
Full Model code with validation........................................................................................................ 66
Step 5 :- Reference “ReactiveFormsModule” in CustomerModule. ................................................. 67
Step 6:- Apply formGroup to HTML form ......................................................................................... 68
Step 7:- Apply validations to HTML control ...................................................................................... 68
Step 8:- Check if Validations are ok .................................................................................................. 68
Step 9:- Checking individual validations ........................................................................................... 68
Step 10 :- standalone elements ........................................................................................................ 69
Complete code of Customer UI with validations applied ................................................................. 71
Run and see your validation in action ............................................................................................... 72
Dirty , pristine , touched and untouched .......................................................................................... 72
Lab 9:- Making HTTP calls ..................................................................................................................... 72
Importance of server side interaction .............................................................................................. 72
Yes , this is a pure Angular book ....................................................................................................... 73
Step 1 :- Creating a fake server side service ..................................................................................... 73
Step 2 :- Importing HTTP and WebAPI module in to main module .................................................. 74
Where do we put the HTTP call ? ..................................................................................................... 75
Step 3 :- Importing HTTP in the Customer component .................................................................... 75
Step 4:- Creating header and request information........................................................................... 76
Step 5 :- Making HTTP calls and observables .................................................................................... 76
Step 6 :- Creating a simple post and get call .................................................................................... 77
Step 7 :- Connecting components to User interface......................................................................... 78
Lab 10:- Input, Output and emitters ..................................................................................................... 79
Theory ............................................................................................................................................... 79
Planning how the component will look like ...................................................................................... 80
Step 1 :- Import input , output and Event Emitter ............................................................................ 80
Step 2 :- Creating the reusable GridComponent class ...................................................................... 81
Step 3 :- Defining inputs and output ................................................................................................. 81
Step 4 :- Defining Event emitters ...................................................................................................... 82
Step 5 :- Creating UI for the reusable component ............................................................................ 84
Step 6 :- Consuming the component in the customer UI ................................................................. 85
Step 7 :- Creating events in the main Customer component ........................................................... 86
Step 8 :- Defining the component in the mainmodule ..................................................................... 86
Lab 11:- Lazy loading using dynamic routes ......................................................................................... 87
Theory ............................................................................................................................................... 87
Step 1 :- Creating three different physical modules ........................................................................ 88
Step 2 :- Removing Supplier and Customercomponent from MainModule ..................................... 89
Step 3 :- Creating different Route files ............................................................................................. 90
Step 4 :- Calling Child routes in Supplier and Customer modules .................................................... 93
Step 5 :- Configuring routerlinks ....................................................................................................... 94
Step 6 :- Replacing browser module with common module ............................................................ 95
Step 7 :- Check if Lazy loading is working ......................................................................................... 97
Lab 12: - Using jQuery with Angular ..................................................................................................... 98
Introduction ...................................................................................................................................... 98
Step 1 :- Install Jquery ....................................................................................................................... 99
Step 2 :- Install Jquery typings .......................................................................................................... 99
Step 3 :- Providing ID’s in the UI ..................................................................................................... 100
Step 4 :- Importing and using Jquery in Component ...................................................................... 100
Step 5:- Make entry in to Systemjs.config.js ................................................................................... 100
Lab 13:- Providers , Services and Dependency Injection .................................................................... 101
Lab 14:- Pipes in Angular ..................................................................................................................... 101
Lab 15:- Going live to production using Webpack .............................................................................. 101
Lab 16:- Pathlocation and HashLocation ............................................................................................ 101
Lab 17:- Auxillary router outlet ........................................................................................................... 101
Lab 18:- Using AG Grid in Angular ....................................................................................................... 101
Lab 19:- Communicating between components using viewChild ....................................................... 101
Lab 20:- Sharing data between modules ............................................................................................ 102
Lab 21:- Change detection .................................................................................................................. 102
Acronym used in this book.................................................................................................................. 102
Angular interview questions and answers .......................................................................................... 102
What is the goal of Angular?........................................................................................................... 102
What is the difference between AngularJS and Angular ? ............................................................. 103
How different is Angular 1.X from Angular 2.X and 4.X ?. .............................................................. 103
What is NodeJs and why do we need it for Angular ? .................................................................... 103
What is the importance of package.json file ? ............................................................................... 104
So how do we install Angular using NodeJs? .................................................................................. 104
Which NPM commands do you use frequently? ............................................................................ 105
What is the use of TypeScript in Angular ? ..................................................................................... 105
What is the importance of tsconfig.json ? ...................................................................................... 106
Explain Components and Modules and how to create them?....................................................... 107
What is the importance of Startup.ts file ?..................................................................................... 107
Explain how a typical angular project loads ? ................................................................................. 107
What is SPA and how to implement in Angular ? ........................................................................... 108
How to make HTTP calls using Angular ? ........................................................................................ 108
How to create reusable UI components? ....................................................................................... 108
Explain input, outputs and emitters ?............................................................................................. 108
How to implement validations using Angular ? .............................................................................. 108
What are services in Angular ? ....................................................................................................... 108
Explain the importance of Pipes in Angular ? ................................................................................. 108
Which grid have you used in Angular ?........................................................................................... 108
What is Webpack and explain its importance in Angular projects ? .............................................. 108
How to use Jquery with Angular ? .................................................................................................. 108
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 you Angular step by step via 20 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 named as just Angular. So when someone says AngularJS it means Angular 1.X and
when some one 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-requisite phase :-In this phase we will four important things Node, Typescript , VSCode , Module
loaders ( SystemJS) and module bundlers ( Webpack).
Main learning phase :- This is where actual angular starts. In this we will be having 8 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.
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.
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.
Understanding versioning system in package.json
Most software versions follow semantic versioning. In semantic versioning versions are divided in to
three numbers as shown in the image below.
As discussed in the previous sections package.json has “^” and “~” versioning mechanism. Now
suppose in your package.json you have mentioned "jquery": "^3.1.0"and Jquery has a new version
“3.2.1”. So in actual it will install or in other words LOCK DOWN to “3.2.1”.
So in package.json you will have “^3.1.0” but actually you will be using “3.2.1”. This entry of actual
version is present in “package-lock.json”. So package lock files have the EXACT versions which are
used in your code.
NPM has huge command list. But here are some very important command which you will need now
and then. As said previously Learn but do not over Learn.
Command Explanation
npm install -g typescript The -g command will install the package globally. In other words in
your computer when you use this package it will take the global
installation. This should be used only for command lines packages
like grunt , typescript, npm and so on.
npm install -save jquery This will install the package and also make a entry in to the
package.json file. Some time we are use a package in our project and
forget to update package.json this comes very handy.
npm view -version jquery This first command will show you latest Jquery version on github and
npm view -versions jquery the second one will show all version in a ascending manner.
npm install -g npm This command updates npm himself. “-g” as discussed in previously
helps to install npm globally.
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.
tsc Customer.ts -w This command will run typescript continuously
in the background and keep looking for
changed files. If the file it will compile that 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.
{
"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.
Point number 6: - Running multiple terminals
One of the things we always need is running multiple command and for that we need a facility to
load multiple terminals.
In VS code we can load multiple terminals by clicking on the plus sign as shown below. So in one
terminal you can run the webserver and in the other terminal you can a code review tool.
By default, VS code shows black theme which is very good for health of your eyes. But sometimes to
just have more code clarity you would like to change to some more brighter theme. You can do that
by clicking on file preferences color theme, you would get themes as shown in the below
figure.
Point number 8: - VS code settings
VS code has lot of settings like you can hide unwanted files and only focus on the files you want,
change icons settings, change font size and so on. To apply a setting, you need to goto File
Preferences Settings and you would be shown a figure as shown below.
In this there are two sections one which has the preference SAMPLE CODE SNIPPETS and the second
section at what level you want to apply these snippets. You can apply snippets at two levels one at a
project workspace level and other at user / computer level.
If you apply at the workspace level its only for that project and if you apply at the user level it will be
applied for all projects in that computer.
For example in the user settings we have pasted the file exclude settings. In this we have specified
we do not want to see the “.JS” and “.Map” files in the workspace.
{
"workbench.sideBar.location": "left",
"window.zoomLevel": 2,
"window.menuBarVisibility": "default",
"files.exclude": {
"**/*.js": true,
"**/*.js.map": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
},
"workbench.colorTheme": "Visual Studio Light"
}
Once that setting is applied you can see the “JS” and “Map” files are not seen.
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”.
All these module formats can be generated
with simple a option change in typescript config
file.
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:- Understanding Module Bundlers using WebPack
In the previous Lab 4 systemJS was doing everything at the runtime. So in the browser it first loads
“Customer.js” then “Address.js” and so on. If you have lot of dependencies you would end up with
lot of requests.
If we can create a SINGLE BUNDLE during the compile time itself, that would be a great performance
booster.
That’s where webpack (
https://webpack.js.org/ ) comes to use.
Webpack is a module bundler.
So the first step is to install webpack. So open the node command prompt and type the below NPM
command. Please see we have use “-g” the global flag.
We take the same code which we have used in “Lab 4”. In lab 4 if you see we have “Customer.js”
calling “Address.js”. So the first Javascript file is “Customer.js”. We just need to give the first JS file
name in the webpack command the final bundle file name. You can also see there is “—output-
library” flag parameter. Webpack will expose “CustomerLibrary” component to us from where we
can access the “Customer” class in the UI.
So now that we have a single bundle we can just load the JS file in the webpage and access the
classes via the “CustomerLibrary”. Remember this “CustomerLibrary” is coming from command line,
please revisit step 2 again for details.
<script src="Bundle.js"></script>
<script>
var x = new CustomerLibrary.Customer();
x.Add();
</script>
If you now see the network tab you will see now only one single file “Bundle.js” as compared to
multiple files.
SystemJS and WebPack. When we learn Angular we will first use SystemJS and then in one of
the labs we will see how Webpack helps us.
So now that we have completed all the prerequisites it’s time to start getting in to Angular. So from
Lab 6 the actual Angular starts.
Lab 6:- 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 let’s start with the first step downloading angular framework and
configuring typescript compiler.
So let’s 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",
"angular-in-memory-web-api": "0.3.2",
"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.8.4"
},
"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.
Common errors during NPM install
This is the most crucial part of Angular. You can see that in “package.json” file we have so many
dependencies and these dependencies use each other. So if one version is incompatible the whole
NPM command will fail. So below are couple of things you need to take care.
To get the latest NPM version you need to use “npm install -g npm”. This command will update NPM
itself.
Also you can get the below error which shows incompatibility between modules. For example in the
below figure it says “For Angular 4.0 you will need Zone.js which is greater than 0.8.4 version.
So go to your project.json , fix the version number , DELETE node_modules folder and do a NPM
again.
Errors of version mismatch can be huge as shown in the below figure. Sometimes fixing
“package.json” can be more painful and iterative. When you do these iterations please ensure you
delete “node_modules” folder so that you are not referring old versions.
You can also get error as shown below “ERR nottarget”. This error says that the particular version
number is not found. Use “npm view packagename version” command to get the latest version and
update your package accordingly.
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"]
}
}
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.
(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',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-
api/bundles/in-memory-web-api.umd.js',
'moment': 'npm:moment',
// ag libraries
'ag-grid-ng2': '../node_modules/ag-grid-ng2',
'ag-grid': '../node_modules/ag-grid',
'jquery': '../node_modules/jquery/dist/jquery.js',
'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'
},
'angular-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);
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 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.
Step 5:- Creating the model
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.
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.
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();
}
// 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.
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.
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 { }
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
});
We also need to run typescript so that TS files gets compiled to JS files. So open the integrated
terminal and type “tsc -w”. This will make typescript run continuously at the background. So as you
type typescript will keep compiling when the file changes.
So if everything is ok in Step 11 we now need to now run http server.To run server we need to type
“http-server” in the VS code integrated terminal as shown in the figure.
Run in two terminals. You can open two terminals by clicking on the “+” in terminal window.
So in one window you can run http-server and in other window you can run typescript in watch
mode.
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 7:- Implementing SPA using Angular routing
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.
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.
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 { }
Router module requires a root path. In other words “Supplier” route would become
“companyname/Supplier” , “Customer” route would become “companyname/Customer” and so on.
If you do not provide a route you would end up with error as shown below.
So in your “Index.html” we need add the HTML BASE HREF tag as show in the highlighted code
below . At this moment we are not providing any root directory.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<base href="./">
<!—Other code has been removed for clarity -->
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.
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.
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.
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)"/>
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:
Example:
<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.
Yes , this is a pure Angular book
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”.
Shiv:- Talk about the sequence of the Httpmodule and Angular Webapi
The next question comes which is the right place to put HTTP calls ?.
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){
}
Step 4:- Creating header and request information
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;
}
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.
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.
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).
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 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);
}
}
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>
<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>
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.
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 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”.
So now the full code look of master page looks as shown below.
@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.
Lab 12: - Using jQuery with Angular
Introduction
jQuery is a very old and trusted JavaScript framework. It has lot of UI components which are stable
and trusted. As a practice, you should not use jQuery with Angular because both of them can overlap
with DOM manipulation causing confusion.
But then there are instances when we would like to use jQuery UI components like jQuery grids,
jQuery calendar and so on which probably are not available in Angular.
If Angular is your prime framework then first see that you get your solution inside Angular if not
then use jQuery or any other framework.
In this lab we will use jQuery to fade away and fade in our grid component. So let’s create a button
with name Hide grid. When the end user clicks on hide grid the grid should gradually become visible
and invisible.
Step 1 :- Install Jquery
So the first step is to get jQuery. Let’s fire up the node command and also let’s get jQuery as well as
lets save the entry in to “package.json” file.
JavaScript is divided in to two generations, one generation before typescript i.e. pure JavaScript and
other generation after typescript. JavaScript is a dynamic and an untyped language while typescript
is strongly typed. We can call methods which does not exist, assign variables which are not created
as so on.
On other side typescript is strongly typed. Everything is done during design time / compile time,
typescript has to know the methods, parameters everything upfront.
Now frameworks like jQuery are made in pure JavaScript, so if they need to be used in typescript we
need to expose their types, parameters and so on. That’s where we need to create typing files.
Typing’s are typescript files which expose the shape and structure of JavaScript objects so that
typescript can understand JavaScript types during design time.
You must be wondering so do we need to create the typing’s file manually ?. No you do not need to.
jQuery already has typing’s on the contrary almost all popular JavaScript frameworks have their
typing’s file.
So to get the jQuery typing’s we need to do npm install by pointing at “@types/jquery”. In fact you
can load any types by using “@types” for example if you want to load lodash you can do “npm
install” on “@types/lodash”.
jQuery references HTML UI elements using selectors. In selectors, we need to provide name or ids by
which we can get reference of that HTML element. So let’s wrap our “grid” component inside a DIV
tag and lets assign some “id” value to it , like the one we have given in the below code “divgrid”.
Also we have created a button which calls the “Fade” methods from the component.
Now the first things is to import jQuery in to your component file. For that we need to use the below
code. You can see the import statement is bit differently used. We are using “*” and “as” keyword.
“*” means we want to refer full JQuery file and “$” is the alias by which we will be referring jQuery
syntax in the code.
Once jQuery has been imported we can now use “$” to execute jQuery syntaxes. You can see we
have created a method called as “Fade” in which we are referring the HTML DIV ID and calling the
“fadeToggle” method to fade in and out.
'jquery': '../node_modules/jquery/dist/jquery.js'
If you see we have specified the folder path as “dist”. “dist” stands for distribution folder. The
final compiled copy of jQuery is in this folder so we have specified the same.
Now run the program and see the output. If you click on the “Hide” button you should see the grid
fading out and in.
Angular is a binding framework which helps to bind HTML UI with JavaScript objects.
In complicated JavaScript projects, you end up writing such kinds of below functions for binding.
These functions bind the UI with JavaScript objects and vice versa.
function UitoObject()
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi()
{
$("#TxtCustomerName").val(Cust.CustomerName);
}
These functions become complicated as the UI gets complicated. Angular is a binding framework and
makes your binding easy.
So when you use Angular you do not need to write the above complicated functions you end up
writing directives as shown in the below code. The below directive “ngModel” will bind data from
the textbox to the customer objects and vice versa.
Angular 1 is called as “AngularJS” while Angular 2 and above is termed as “Angular”. So when you
say “AngularJS” you are referring the “1.X” version and when you say Angular you are talking about
the new version.
Angular 2 is completely different from Angular 1. The syntaxes and project structure are completely
different. We can not automatically migrate an Angular 1 project to Angular 2.
While Angular 2 and Angular 4 are backward compatible. Angular 2 projects can work with Angular 4
framework without any tweak.
NodeJS has something called as NPM (Node Package Manager). Using NPM we can install any
JavaScript framework. So once you install node , you can go to Node command prompt and type
command as shown in the below figure.
So in Angular projects NPM is used to install Angular framework.
“package.json” file is a feature provided by Node. Rather than writing NPM commands again and
again. You can create a “package.json” file listing all dependencies as shown in below code and just
fire “NPM INSTALL” command. That will install all the packages mentioned in the file.
{
"name": "test",
"version": "1.0.0",
"description": "",
"dependencies": {
"jquery": "^3.2.1",
"knockout": "^3.4.2",
"lodash": "~4.17.4"
}
}
To install Angular you need to create a “package.json” file with all Angular dependencies listed and
then do a NPM INSTALL on the folder where this file is. This file is available on the main site of
Angular as well.
{
"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",
"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.8.4"
}
}
NPM has huge command list. In these kinds of questions interviewer is expecting you to talk about
common NPM commands. So below are some important ones.
Command Explanation
npm install -g typescript This installs the package globally.
npm install -save jquery This will install the package and also make a entry in “package.json”
file.
npm view -version jquery This first command will show you latest Jquery version on github and
npm view -versions jquery the second one will show all version in a ascending manner.
npm install -g npm This upgraded NPM to latest version
TypeScript is a transpiler over JavaScript. It provides sugar coated syntax over JavaScript where
developers can apply OOP principles like class , inheritance , interfaces and so on.
Once you hit compile typescript will transpile the code to pure Javascript.
To compile code we need run “tsc” from command line.
“tsconfig.json” defines how typescript compiler will compile. Below is a simple code snippet of
tsconfig file which says that compile using ES 5 specifications , remove comments and put all
compiled JS files to “Shiv” directory.
{
"compilerOptions": {
"target": "es5",
"removeComments": false,
"outDir": "/Shiv"
}
}
Explain Components and Modules and how to create them?
Components have the binding code which binds the view with the model. While modules group
these components. So in complex angular project can have “Customer component” , “Customer
reporting component” which is grouped in “Customer module”. In the same project you can have
supplier module which groups 1 or many supplier components.
In a complex angular project you can have lot of modules like home module , supplier module and so
on. “Startup.ts” file states which of the module will become your startup module.