Learning Angular 2 for newbie – Part 2

Ahteshamax
Posted by in Angular 2 category on for Beginner level | Points: 250 | Views : 1477 red flag

In this article before we start with the Angular2 project first we will understand Angular2 component and module architecture thereafter we create simple application.

This article is the Part 2 and continuation of Part 1 where we have covered downloads and installation part. In this article before we start with the Angular2 project first we will understand Angular2 component and module architecture thereafter we create simple application and will display output screen.

New terminologies used

Component: It will have binding logic in order to bind UI(html) with the Model(Business)

Module: It is nothing but logical grouping of component.

Project Structure

To create a project structure we will first create four folders in our project:-

  1. Model folder: - This folder will have the main business logic create using typescript classes.
  2. Component folder: - This folder will have the binding code which binds the HTML UI and Model.
  3. Module folder: - This folder will have code which will logically group the components.
  4. UI or View folder: - This folder will contain the HTML UI(User Interface).


Model

For Project Structure, first we will create Model folder now in order to create a folder in VS code you can use the “New folder” icon option given on top as shown in the image down below. Similarly new Business “TypeScript” file can be created by clicking on the icon.

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.

Mark “Customer.ts” file with export syntax so that it can be called by other files. It will be used by Customer component.


Component

The second thing we need write a code which is the binding code. Binding code in Angular 2 is officially called as “COMPONENTS”. Angular 2 components are written with binding logic which helps to bind the UI with the model.

Now under the Component folder created create an new”CustomerComponent.ts” we need to import two things the Angular 2 core and our Customer model. Please note “import” is a “TypeScript” syntax and not JavaScript. So in case you are new to TypeScript and not getting the syntax, suggesting you to refer Typescript video. Following are the lines of code

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

The first line imports the “Customer” class from the Model folder into our “CustomerComponent.ts”. And the most important thing is that import becomes only possible because when we have written “export” in “Customer.ts” file or else it will show red underlined error. The import and export generate code which follows CommonJSspecifications and we have used this only other types of specifications are AMD or UMD. We recommend referring CommonJS specifications video explaining complete in more detail.

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

As said earlier that component does binding with model to the HTML UI. So there should be some code which tells that “CustomerComponent” is bounded with HTML UI. In the below shown code which starts with “@Component” and 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"
})


Customer HTML UI

If you have seen above from “CustomerComponent.ts” within Component, “Customer” is exposed via the “CurrentCustomer” object to UI. So in HTML UI we need to refer this object while binding.

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


For example in our code, if we want to bind “CustomerName” with HTML textbox code then “[(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”. This is because the object exposed from the “CustomerComponent” is “CurrentCustomer” object. So you need to write complete “CurrentCustomer.CustomerCode”. Similarly we have write to code for “CustomerCode” and “CustomerAmount”.

<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

Followed by that create a Module folder as said earlier Module is logical grouping of all Components.In Module folder create “TypeScript” file with name “MainModuleLibrary.ts” which will have all necessary components required loading in it.

So the first line here is to write code which will import in this module is the “CustomerComponent” component.

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

Thereafter we also need to import “BrowserModule” and “FormsModule” from core angular. “BrowserModule” has components with the help of which we can write IF conditions and FOR loop. “FormsModule” gives directive functionality like “ngModel”, expressions and many others.

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

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

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

If you see in the code you will find that “NgModule” has three properties:-

  1. Imports: - If this module is using/consuming other modules we have to define the same modules in this section.
  2. Declarations: - Under this we will declare the components of those modules. For now we only have one component ‘CustomerComponent”.
  3. Bootstrap: - This part will define first component which will run when application starts.
@NgModule({
    imports: [BrowserModule,
             FormsModule],
    declarations: [CustomerComponent],
    bootstrap: [CustomerComponent]
})

We also need to create a TypeScript class “MainModuleLibrary”. Right now at this moment this class do not have any code as such but later it can have code which will give component level logic like caching, initialization code for those group of components and so on.

export class MainModuleLibrary { }


Startup folder: Startup.ts

Next important is to create Startup folder under which it will have “TypeScript” file with name “Startup.ts”. Within this “Startup.ts” file we will have name of the module which will be loading first platform.bootstrapModule(MainModuleLibrary)

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

Below is the snapshot of the Startup.ts file created within Startup folder as shown in the image down below.


Invoke “Startup.ts” using Index page

Under “UI” folder go and create “index.html” page which will have following lines code and help to invoke “Startup.ts”. In this index.html page we will need to import four JavaScript framework files Shim , Zone , Meta-data and System JS.

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

Below mentioned is the uses of each JS files:-

Shim.min.jsThis framework helps and ensures that ES 6 JavaScript can run in old browsers.
Zone.jsWith the help of zone.js it treats group of async activities as one zone.
Reflect.jsUseful to apply meta-data on JavaScript classes. Over here we are currently using @NgModule and @NgComponent as attributes.
System.jsThis module will helps to load JS files using module protocols or which specification to follow like commonjs , AMD or UMD.

In “index.html” page we will are going to call “systemjs.config.js” file. This file will tell systemJS which files to be loaded in the browser.

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

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

Below line of code need to be written which will “import” and that we need to specify in “startup” which will help to invoke “startup.js” file.

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

Our “Customer” screen is 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 above we have created component class we does the work of loading HTML page in a selector. So that mentioned selector is nothing but a tag (placeholder) to load our Customer page.

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


Now “Build” your entire solution using “ctrl+shift+B” combination keys on keyboard. If everything is correct it will “Build” entire solution which we see under the Explorer will generate “.js” and “.map”file for “.ts” file used in the project.

Running Server

Now everything is fine “Build”. Next task is to either install server to run the application like http-server or can run it on in-built server. In this part we will use here in-build server called “lite” server. For that click on “Integrated Terminal” this option is available under “View” of the Menu bar as shown in the below image.

Once the command prompt is open write the command to run “lite” server

npm run lite


It will open the browser where we have to give the page name which is “index.html” which will open “Customer.html” page. If everything is correct it will show the output at the bottom when textbox is filled with data as shown in the image down below.


Feeling bored by reading this article get yourself refreshed with step by step video on Angular2: -

Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)