Lab 1 - Learn Angular 2 step by step for Beginners

Hello Friends, Welcome To Learn Angular Tutorial Site, Here in this is session or part 1 article of learn angular step by step series we will learn following as mentioned below.

Source Code Of This Lab - Download

 

Overview

This is just Lab 1 of Learn Angular 2, further this learn-angular lab series is divided into 10 parts / 10 Labs. so make sure you read all our labs one by one throught out a week. Each of our labs are guided or explained with detailed step by step.

We just believe in step by step project wise and it is one of the best way to learn any new technology in project wise. So lets continue this article in projectwise for the same Let's create creating a simple Customer data entry screen project as shown in below image.

So for Lab 1 we will make a fundamental display in which we will make three fields "Name" , "Code" and "Amount". When the customer / end-user types in these 3 fields the values will be shown down below.

So in lab 1 we will perform 11 actions to get the same.

It is quiet a huge article to read so for the same to cut-short you can watch our Angular 2 video in this we have explained Angular 2 video program.

Note : In this video we have use Visual Studio tools while this article is in VSCode so that Microsoft code feel happy and Non-Microsoft guy feel comfortable. Check out our video below

Short Forms Used in Article

  • OS : Operating system.
  • NPM : Node package manager.
  • VS Code : Visual studio code.
  • JS : Javascript.
  • VS : Visual studio.
  • WP : Webpack
  • TS : TypeScript.

Goal of Angular 2

"Angular 2 is an free JavaScript framework which makes easier binding code between JavaScript objects and HTML UI elements"

Let's try and understand this above statement with a sample code.

Here is a simple function called "Customer" with "CustomerName" property. Below function we have created an object called as "Cust" of "Customer" class type.

function Customer() 
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();
<input id="TxtCustomerName" onchange="UitoObject()" type="text" />

Now let's suppose we would like to bind above customer object to a HTML textbox called "TxtCustomerName". In other per say if we change anything in HTML text box (UI side) the customer object should be updated and same vice versa like if a object is updated then UI should get updated.

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

As you see in our above code to achieve communication between HTML UI to customer object developers end up writing functions.

UitoObject : Takes data from UI and bind it to customer object.

ObjecttoUI : Takes data from cust object and bind it to HTML UI.

So if we analyze closely both functions are nothing but your binding logic which transfer data from one-end to other-end.

Same code can be written in an Angular as shown below like whatever type in textbox it get updates to customer object.

<input type="text" />

Let's see the code visually as displayed below.

Here the view is HTML and Model is customer object and Angular Javascription fuctions acts like whatever (View Model, Presenter or Controller) depending on situations.

Some developers call this as "ViewModel" because it connects View and the Model. Some call it as "Presenter" because logic is presentation logic. Some terms it as "Controller" because it controls data flow from view to model. so whatever we call it, It will function as per "WhatEver" binding logic. Thats why many developers as we also call Angular implements "MVW" architecture.

Goal of an Angular is nothing but Binding data...Binding and Binding.

Requirement before you start Angular 2

To gets started learning Angular 2 we realized that Angular 2 by itself is easy to understand but Angular 2 uses lots of open sources like NodeJS, Type Script, SystemJS and CommonJS so if you do not know these topics it would be very difficult to understand Angular 2.

We highly recommend that spend some time understanding these topics before starting up Angular.

Here's are our some videos for quick brush up on open source topics as listed below.

Node JS

https://www.youtube.com/watch?v=-LF_43_Mqnw

System JS

https://www.youtube.com/watch?v=nQGhdoIMKaM

Type Script

https://www.youtube.com/watch?v=xqYD8QXJX9U

Common JS

https://www.youtube.com/watch?v=jN4IM5tp1SE

Step 1 : Installing VS Code, Node and Typescript

Ideally you can do Angular 2 code in a simple notepad or in notepad++ but it would be like going back to adam and eve era.

So here we recommend expedite the coding process use some tools and software and same we are going to use to code Angular 2

First Tool : You need Visual Studio code editor (VS Code). Here is the link to download depending on your operating system like for instance we have windows OS so we have downloaded windows version. https://code.visualstudio.com/download

Once you have downloaded the setup -> run setup EXE run it and just follow the button instruction to finish.

Second : We need NodeJS for the same we have video which explains the basic use of Node JS https://www.youtube.com/watch?v=-LF_43_Mqnw

NodeJS does the following two things

1 : It has "NPM" node package manager. NPM is a central repository where all updated javascript or jquery files are registered. If you see there are many javascript(JS) frameworks coming up every day. Each one of these frameworks have their own website, github repository with peculiar names and releasing new versions now and then and to get these frameworks we need to go to their site/github to download framework JS files and so on. Here at NPM if a coder wants to get a specific JS open source he can just type NPM commands like "npm install jquery". This command will get the recent version of JS files in your computer system folder.

2 : The second thing in which nodeJS helps in that you can able to run JavaScript outside the browser means tomorrow if you want to build any windows application or server application using JavaScript then this thing might help.

In order to get NodeJS just visit www.nodejs.org and depending on your operating system select the suitable to download as shown in the below image.

Once you have successfully installed nodeJS you should able to see NodeJs command prompt in your program files as shown in the image. Now using this command prompt you can run NPM commands.

If you still have some doubts on using NodeJS or NPM then watch our video which explains NodeJS in more details.

Third : Angular 2 needs is Typescript.

"TypeScript is a sugar coated Object oriented programming language over JavaScript."

So in typescript we can write or use keywords like "class", "extends" , "interface" and so on.Internally typescript will compile or transpile into pure javascript code in terms of functions ,closures and IIFE.

To catchup more about typescript request you to watch our video on Typescript : https://www.youtube.com/watch?v=xqYD8QXJX9U

Like NodeJS typescript is also an open source framework and in-order to get it we just need to use NodeJS command prompt that is NPM command i.e. "npm install –g typescript" . This command installs typescript in your PC and makes it available global throughout the computer.

Note :- The "-g" command makes typescript available globally in the computer from any folder command prompt.

Inorder to start with Angular we need these three things that is First VS Code editor , Second NodeJS (NPM) for getting JavaScript frameworks and Third Typescript so that we can code JavaScript faster and with OOPS coding approach.

Modularity comes with great responsibility

In Angular 1.X we just had one JS file which had the whole framework. So there we just need to drag and drop that single Angular 1.X JS file on HTML page folder and thats it you are ready with the Angular 1.X environment. But problem with that approach is it is one JS file framework which includes all features even if you need it or not. For example if you are not using HTTP feature then still that feature will be loaded.

In case of Angular 2 here we have separate and self-contained components which can be loaded in an isolated manner somewhat than loading the whole JS file.

Now that we have lot of self-contained components JSON files, Creating a proper environment itself is a question. So let us first understand how to setup angular environment.

Step 2 : Setting up Angular 2 environment

So the first step create a folder and open the folder using VSCode as shown in the below image.

Inside this folder paste the 4 JSON files. To simply things we have updated these 4 JSON files at our source and you can access/download these files from this URL [tinyurl.com/jeehlqo].

Note : These files we have not created these files but we got them from Angular 2 website or the respective open source website.

4 JSON files explained

package.json

package.json file has the reference for all the Angular 2 modules. Node will use this .json file to download all the Angular modular files.

systemjs.config is a module loader. This configuration file defines the configuration for SystemJS module loader.We will talk more in-detail about this module loader in our coming steps.

typings.json

Typescript is a new js language and some of the old JS frameworks cannot be consumed in typescript. So particularly for those old frameworks we need to define the typings json.

systemjs.config

tsconfig.json

tsconfig.json is a configuration file for typescript and will be used by typescript to define how transpiling/compiling process takes place in typescript.

So now lets open "nodejs" command prompt and type "npm install" in the command line to get all the files which are mentioned in the package.json file as shown in below image.

Note : Internet Should be in Connected state. If you are not connected to internet then you get an error as shown in the below image.

once Angular installation is done successfully you will see a "node_modules" folder created. In this folder you will see all the downloaded JS files.

Step 3 : Configuring the task runner

VSCode is just a code editor. It has no idea how to compile/transpile and run typescript code. So inorder run and transpile typescript code to JavaScript we need to create a GRUNT task.

To create GRUNT task press CTRL + SHIFT + B and click on configure task runner as shown in the below image.

VS Code then pops up lot of task runner options like GRUNT task, GULP task, MSBUILD, MAVEN etc. select GRUNT task and move ahead.

Once you select GRUNT Task, paste the below JSON code. Once you paste it you will see that it has created a file called as "tasks.json" file inside ".vscode" folder.


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

Above code is from "tasks.json" file. You can see in the command attribute we have given "tsc" as the command line, the "isShellCommand" specifies that this has to be executed in command line and 'args' specifies the argument.

When a typescript will execute it will run using the configuration specified in the tasks.json file. So if you now press CTRL + SHIFT + B it will build the TS files to JS files.

Understanding Angular 2 Component and module architecture

Whole goal of Angular 2 is binding the model and the view and in Angular 2 the binding code is officially termed as "Component". So hence we will use the word "Component" instead of binding code.

In an enterprise projects you can have lot of components and it can become very complicate to handle the project. So for that you can group components logically into modules.

So next off we will be using two terms :

Components : This will have the binding logic to bind the UI and the model.

Modules : This will logically group components.

Step 4 : Following MVW Step by Step - Creating the folders

Before we start our actual coding lets visualize the steps of coding. As we know that Angular 2 is all about binding framework i.e. MVW architecture (Model-View-Whatever) which is nothing but binding JavaScript code with HTML UI.

So if we imagine it will appear something as shown in below image . So let's move from right -> left. So let's do it :

We will Create model.

Then we will Create Component.

Then we will Create module.

Then we will Create HTML UI.

So let's first create four folders in our project :

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

Model folder : - This folder will have the typescript classes (business).

Component folder : - This folder will have the binding code which binds the HTML UI and Model.

Module : - This folder will have code which will logically group the components.

In order to produce a folder in VScode editor you can use the "New folder" option from icon or you can right click and also create a folder.

Step 5 : Creating the model

A model is nothing but a class with properties and behavior. So let's create customer class with three properties "CustomerName", "CustomerCode" and "CustomerAmount".

So right click on the "Model" folder and add a new file "Customer.ts". ".ts" an extension for typescript file.

While compiling the typescript command identifies only files with the extension ".ts".

In this typescript "Customer.ts" file let's create a "Customer" class with three properties "CustomerName", "CustomerCode" and "CustomerAmount".

export class Customer {
    CustomerName: string = "";
    CustomerCode: string = "";
    CustomerAmount: number = 0;
}

Step 6 : Creating the Component

Now we need to create the binding code as we discussed earlier it is termed as "COMPONENTS".

So right click on the component folder and add "CustomerComponent.ts" file as shown in above image.

In this component we need to import two things i.e. the Angular 2 core and Customer model. Kindly note "import" is a typescript syntax and not JavaScript. syntax In case if you are not following the code then kindly watch our Learn Typescript in 1 hour video https://www.youtube.com/watch?v=xqYD8QXJX9U.


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

As you saw in above code imports {Customer} imports "Customer" class in to the "CustomerComponent.ts". And this import is only feasible because we have written "export" in "Customer.ts" file.

This import and export syntax generates code which follows CommonJs in AMD or UMD specifications. In case if you want to understand more about these specifications please see this video which explains the CommonJs protocol in more detail.https://www.youtube.com/watch?v=jN4IM5tp1SE

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

Let's understand how "Customer" component is located. If you see it is using a relative path and in the import it says "../Model/Customer".

The "../" says go one folder up. So we are currently using in the "Component" folder "../" it travels to the root and from that point it makes entry in to the "Model" folder.

The next below code import command for angular core components. In this we have not given any relative path using "../" then how does typescript can locate the angular core components ?.

import {Component} from "@angular/core"

If you recall we have used node to load Angular 2 and node loads the JS files in the "node_modules" folder. So how does typescript compiler automatically understand that it has to load the Angular 2 components from "node_modules" folder.

Typescript compiler uses the configuration i.e. "tsconfig.json" file. In this configuration file we have one property named as "moduleResolution". It has two values :- Classic and Node respectively

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 file we have defined mode as "node" this makes typescript to find modules automatically in "node_modules" folder. Thus makes the "import" of angular 2 components work.


{
 {
  ....
  ....
    "moduleResolution": "node",
 ....
 ....
  }
}

So for now both the import statements are applied now let's create the "CustomerComponent" and from that let's expose "Customer" object to the UI as an object name "CurrentCustomer".

export class CustomerComponent {
    CurrentCustomer:Customer = new Customer();
}

As we discussed earlier that component connects or binds the model to the HTML UI. So there should be some code which tells that "CustomerComponent" is bounded with HTML UI. That's declared as termed as "Component MetaData Attribute".

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. As shown in below code snippet.

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

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

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

In simple words binding code is nothing but a simple typescript class which ornamented by "@Component" attribute which state that this typescript class is binded with which HTML UI.

Below goes the full code of the Angular component.


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

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

Step 7 : Creating the Customer HTML UI – Directives and Interpolation

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

In the HTML UI an object is binded by using "Directives". Directives are tags which direct how to bind with the UI.For an example if we want to bind "CustomerName" with HTML textbox as shown in below snippet of code.

"[(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 an object. It's referring the property as "CurrentCustomer.CustomerName" and not just "CustomerName". Why ??. Because if you remember an object exposed from the "CustomerComponent" is "CurrentCustomer" object. So you need to qualify "CurrentCustomer.CustomerCode".

<input type="text" />

  • Square brackets indicates that data is sent from object to UI.
  • Round brackets indicates that data sent from UI to object.
  • If both are present then it's a two way binding.

If we want to display object data on the browser then we can achieve that by using "{{" braces (Termed as "INTERPOLATION") along with HTML tags. Here below in our HTML page we are displaying "CustomerName" mixed with HTML tag. If you see the oxford dictionary meaning of interpolation it means inserting something of different nature in to something else.

Here below code we are inserting object data within HTML.

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

Step 8 : Creating the Module

Meaning : Module is a logical grouping of components and other services like an container.

So let's import "CustomerComponent" in this module.

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

We also need to import "BrowserModule" and "FormsModule" from core angular. "BrowserModule" has components by which we can write FOR loops and IF conditions. "FormsModule" provides directive functionality like "ngModel", expressions and so on.

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

We also need to create a typescript class i.e. "MainModuleLibrary". At this moment class does not have any code but it can have code which will give component level logic like initialization and caching for those group of components and so on.

export class MainModuleLibrary { }

To create a module we have to import "NgModule" from angular core thus helps us to define module directives.

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

"NgModule" has got three properties :- Declarations, Imports and Bootstrap.

Bootstrap : Here in this it defines first component which is going to execute first like for instance here we have two components i.e. CustomerComponent and HomeComponent and first component which we want to execute is HomeComponent so that we need to define here.

Imports: If we want to define any module to import in this current module then we can define here in this section.

Declarations: Here we can define component of module. In this session we have only one component i.e. CustomerComponent so we will define here.

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

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

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

Step 9 : Creating the "Startup.ts" file

So till now we have created modules, components which are grouped in a modules. As we know in Angular we can have many modules to make any one module as start up. So to define that we will create Startup.ts file.


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { MainModuleLibrary } from '../Module/MainModuleLibrary';
const platform = platformBrowserDynamic();
platform.bootstrapModule(MainModuleLibrary);

Above code is defined in Startup.ts file.

Step 10 : Invoking "Startup.ts" file using main angular page

Now that we have created Startup.ts file lets invoke this file in our angular page for the same we will create HTML page which will invoke the "Startup.ts.

In our current HTML page we need to add or import some Javascript frameworks like Shim, System, Reflect and Zone as shown in 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>

Zone.js : This framework ensures us to treat group of Async activities as one zone.

Shim.min.js : This framework ensures to javascript code in old browsers (IE6 and so on).

Reflect.js : Helps us to apply meta-data on Javascript classes like @NgModule and @NgComponent as attributes.

System.js : This module will helps to load JS files using module protocols like AMD or UMD, commonjs.

Below here we are calling systemjs.config.js file just to tell system JS which files to be loaded in browser.

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

    System.import('startup').catch(function (err) { console.error(err); });
</script>

In the import we need to specify startup which will invoke startup.ts file as shown in below code.

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

Our customer page i.e. "Customer.html. So to load in to this page we need to define a place holder. so let's define it as shown in below.

<customer-ui></customer-ui>

Let's define this Customer.html page in component class in a selector attribute.

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

As you see friends we have defined our html page in the placeholder i.e. selector attribute. Just check our below code of full html

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

    System.import('startup').catch(function (err) { console.error(err); });
</script>
<body>
    <customer-ui></customer-ui>
</body>
</html>

Step 11 : Installing http-server and running the application

Final stage of this article where we need to install http-server and run this application. So do that. In order to run this app we require web server. So to get that just go to integrated command terminal and type this command "npm install http-server". This http-server useful for testing app in our local server or PC.

To run this server we need to type "http-server" in the VScode integrated terminal as shown in above figure.

In case your 80 port is blocked you can type this command "http-server –p 99". This will run this server over 99 port.

Finally once web server is up and running you can now browse the application HTML page i.e. our main angular HTML page where we have added all our codes.

Note: Customer.html is not our main startup page , this page will be loaded in the placeholder of our angular page.

Just type anything in textboxes as shown above image see the automation of binding output in expression.

How to the run the source code?

Source Code For Download

This is our source code link of this lab or lab 1.

Note : We have attached this source code without "node_modules folder. So to run the code you need to open the folder using VScode editor and then do a NPM using the command integrated terminal on the folder where you have "package.json file. Please read our step 2 if still issue or query kindly let us know.

So hey friends this all about Lab 1 or Part 1 in our coming part 2 we are going to implement single page application using Angular 2 routing so do come back to read part 2 article very soon.

If you really like this article do not forget to share with your colleagues / team mates / friends on social media channels (FB, Google+, Twitter, LinkedIN).

+91-22-66752917
+91 9967590707
questpond@questpond.com / questpond@yahoo.com