Getting Started with Angular 2 using TypeScript :-

Step 1 : First of all we will install Node.js and NPM in our OS.

Step 2: Inside the project root folder, we will createpackage.jsonand then we will run npm install using command prompt navigating to root directory of the project. It will create node_modules folder parallel to package.json.

Step 3 : Then we will create tsconfig.jsonthat contains the configuration for how the TypeScript code will compile into JavaScript.

Step 4: Now we will createsystemjs.config.jsthat will contain mapping for all the packages required.

Step 5: Now we will create our demo project. Create a directory such as app in root directory of the project, we will create component, its HTML template, styles, module and main typescript files. We will also create index.htmlin root directory of the project.

Step 6: From the root directory, we will run npm install using command prompt that will download all the required libraries and then run npm start command that will compile all the TS files into JS files and will continue to observe for any change in our files in development mode.

Contents

Software Used

Find the software used in our demo.

  1. Angular 2.3.0

  2. TypeScript 2.0.10

  3. Node.js 4.6.0

  4. NPM 3.10.8

  5. Firefox 50.1.0

Install Node.js and NPM

To work with angular 2, we need to make sure that

Node.js

version must be 4.x.x or higher and for

NPM

it must be 3.x.x or higher. Now follow the below steps.

  1. Download latest version of

Node.js

using the

  1. Install

Node.js

and upgrade npm version by running the command using command prompt as follows.

npm install [email protected] -g

Here 3.10.8 is target npm version. Find the

link

for the reference.

  1. Use the following command to check the node and npm version.

node -v

: It checks node version.

npm -v

: It checks npm version.

Project Structure

Find the structure of our demo project.

Create package.json

To download all the angular 2 dependencies we are using node and npm. Node.js uses

package.json

file to take user input for angular 2 dependencies. In

package.json

we configure all angular 2 dependencies. Here we will discuss some important fields of

package.json

.

name and version

: These two are the most important fields in

package.json

. These are the required fields and package will not install in the absence of these fields.

name

and

version

together form an identifier and must be unique. Whenever we do any changes in package, we need to change version, too.

scripts It contains commands that run at various times in package life cycle. The

key refers to event name and

value is command that runs at that point.

dependencies : It maps a package name to a version range. Package name can be like

myPackage ,bootstrap ,@angular/common

etc. Version range can be like >=version,<version,<=version ,~version,^version etc.

devDependencies : Here we define external test or documentation framework that we use in our module. If someone is using our module, then it is possible that they will not use our development dependencies, so it should be separate from

dependencies field. Find the package.jsonused in our example. We need to put it in our project root folder.

package.json

When we run npm install , it creates node_modules folder within the root folder of the project. In node_modules folder all the packages and its dependencies configured in package.jsonare downloaded. Find the print screen for running

npm install

command using command prompt.

Now look at the code snippet in

To compile TypeScript into JavaScript, we need to run following command.

tsc

: This command will compile TypeScript file into JavaScript file and will exit.

tsc -w

: This command will compile TypeScript file into JavaScript file as well as continue to observe for any change in TS files. If there is any change in TS file, then the TS files will compile again in JS files.

We can also write the above script as shown below.

Here first

tsc -w

is using alias as

tsc:w

and then

start

event is using

npm run tsc:w

that will ultimately run

tsc -w

command.

Create tsconfig.json

tsconfig.json

is a JSON file that is used to define how the TypeScript compiler compiles TypeScript code of project file to JavaScript code . This file should be located in the root folder of the project. We need to run

tsc

command within the root folder of the project. We configure this command in

package.json

in scripts field. Now find some compiler options configured in tsconfig.json .

target: It specifies ECMAScript target version. Default is

es3.

module: It specifies module code generation.

moduleResolution: It determines how modules get resolved.

sourceMap: It generates

.map

file corresponding to

TS

file.

outDir

: It redirects output structure to the given directory. We can use it such as

"outDir": "app/compiled-js"

.

experimentalDecorators

: It enables experimental support for ES7 decorators.

lib

: We need to assign required list of library files in the compilation. The possible values are ES5, ES6, ES2015, ES7, ES2016, ES2017, DOM etc.

Now find the

tsconfig.json

file used in our example.

tsconfig.json

ES2015

:

ES2015 is the 6th edition of ECMAScript. ECMAScript is the standard name of JavaScript. ES2015 is also known as ES6. According to new naming convention, ECMAScript versions are named using yearly model for defining new JavaScript standards. In this way the other ECMAScript versions are ES2016 and ES2017 on the basis of yearly model. We should use ECMAScript version on the basis of browser compatibility. The higher version of ECMAScript does not support lower versions of browser.

In package.jsonwe have configured start event as follows.

And when we run

npm start

then

tsc -w

command will run. If we use

tsc

command then that will compile the TS file into JS and if we use

tsc -w

, it will compile as well as continue to observe for any changes in our TS file to compile again. Hence in our development phase we need not to worry about compilation every time. In our example we are using

tsc -w

command. Find the print screen of output when we run

npm start

If there is any syntax error in TypeScript file, then it will not be compiled in JavaScript files. Error will be displayed in command prompt after running

npm start

command. We need to look into error and fix it. This is compile time error.

Find the links of

tsconfig.json

references.

tsconfig.json Overview

Compiler Options

Create systemjs.config.js

SystemJS is universal dynamic module loader that loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS. It supports RequireJS-style map, paths, bundles and global shims. Here in our example we are creating SystemJS configuration file as

systemjs.config.js

that will provide information to a module loader. It helps to find application module and registers all the required packages. Find some SystemJS API used in our example.

System.config

: This function sets configuration on SystemJS. Here we configure paths, map, packages etc. Find the reference

System.import

: It imports application. We use it as follows in

index.html

.

Now find the SystemJS configuration file,

index.html

and CSS file used in our example.

systemjs.config.js

(
function
(
global
)
{
System
.
config
({

    paths
:
{
'npm:'
:
'node_modules/'
},

    map
:
{

      myApp
:
'app'
,
'@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'
,
'rxjs'
:
'npm:rxjs'
,
'angular-in-memory-web-api'
:
'npm:angular-in-memory-web-api'
,
},

    packages
:
{

      myApp
:
{

        main
:
'./main.js'
,

        defaultExtension
:
'js'
},

      rxjs
:
{

        defaultExtension
:
'js'
},
'angular-in-memory-web-api'
:
{

        main
:
'./index.js'
,

        defaultExtension
:
'js'
}
}
});
})(
this
);

System.config()

defines following properties.

paths

: Here we create alias for paths. In our file we are writing as below.

'npm:'
:
'node_modules/'

The above line of code means that

npm:

is the alias for

node_modules/

that is the directory for all angular libraries.

map

: It maps a value into a property. Find the line of code.

'@angular/core'
:
'npm:@angular/core/bundles/core.umd.js'

It means when we import

@angular/core

in our component, we actually import

node_modules/@angular/core/bundles/core.umd.js

packages

: It defines packages. Find the line of code.

myApp
:
{

      main
:
'./main.js'
,

      defaultExtension
:
'js'
}

When we call

System.import('myApp')

, it imports

main.js

from the directory

app

because it has mapped as

myApp: 'app'

in mapping block.

typings

Here we will understand

typings

and its use. Angular provides

typings

itself and we have to do nothing for this step.

Angular uses JavaScript environment, its features and syntax that the TypeScript compiler doesn't recognize natively. So while compiling it throws error. To avoid error we have to use TypeScript type definition files that are

d.ts

files. In angular

node_modules/@angular/core/

folder contains several

d.ts

files.

In angular application development we need to do nothing to get typings.

But if we want to create

typings

separately we can do it. To perform this task we need to provide

typings.json

file. The packages can be installed from Typings Registry, GitHub, NPM, Bower, HTTP and local files.

typings

will ensure that they will never conflict in versions. To create

typings.json

and to use it, find the below steps.

  1. Open command prompt and install

typings

using the following command.

npm install typings -global

Run the above command only if

typings

has not been already installed. After this installation we will be able to run

typings

command.

  1. We will add

core-js, jasmine and node

packages in

typings.json

file as global dependencies. Go to the root folder of the project and run the following command one by one. These commands will create

typings.json

file and adds the specified packages.

typings install dt~core-js --global --save

typings install dt~jasmine --global --save

typings install dt~node --global --save

Now go to the root folder of the project. We will find a file named as

typings.json

and a folder named as

typings

. This folder will contain

index.d.ts

file for

core-js, jasmine and node

packages.

typings.json

file will be created as follows.

typings.json

{
"globalDependencies"
:
{
"core-js"
:
"registry:dt/core-js#0.0.0+20160914114559"
,
"jasmine"
:
"registry:dt/jasmine#2.5.0+20161003201800"
,
"node"
:
"registry:dt
ode#6.0.0+20161019125345"
}
}

For the

typings

command reference, find the

link

.

Create Component, HTML Template and Styles

The syntax of component from Angular doc using TypeScript is as follows.

@Component
({...})
class
MyComponent
()
{}

Find the component used in our example.

app.component.ts

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

  selector
:
'msg-app'
,

  templateUrl
:
'app/app.component.html'
,

  styleUrls
:
[
'app/app.component.css'
]
})
export
class
AppComponent
{

   message 
=
"Hello Angular 2 World with TypeScript"
;
}

@Component

decorator has been defined in angular

core

package. So we need to import it using

import

keyword. To import

@angular/core

in component means we actually import

node_modules/@angular/core/bundles/core.umd.js

To understand

@angular/core

mapping with complete path, refer the file

systemjs.config.js

given in this example. Now find some metadata of

@Component

decorator.

selector

: Defines component element.

templateUrl

: Defines HTML template URL.

template

: Here we can write inline HTML code.

styleUrls

: Defines styles.

Find the HTML template of

AppComponent

component.

app.component.html

<
h1
>
 {{message}} 
<
/h1
>

In above HTML template we are fetching value of component property

message

defined in

AppComponent

. Now find the CSS used in our example.

app.component.css

h1 
{

  color
:
#369;

  font
-
family
:
Arial
,
Helvetica
,
 sans
-
serif
;

  font
-
size
:
250
%;
}

The above CSS has been defined in

AppComponent

, so this CSS will be applied only in its HTML template that is

app.component.html

.

Create Module

The syntax of module from Angular doc using TypeScript is as follows.

@NgModule
({
 declarations
:
...,
 imports
:
...,

     exports
:
...,
 providers
:
...,
 bootstrap
:
...})
class
MyModule
{}

Now find the module used in our example.

module.ts

import
{
NgModule
}
from
'@angular/core'
;
import
{
BrowserModule
}
from
'@angular/platform-browser'
;
import
{
AppComponent
}
from
'./app.component'
;
@NgModule
({

  imports
:
[
BrowserModule
],

  declarations
:
[
AppComponent
],

  bootstrap
:
[
AppComponent
]
})
export
class
AppModule
{
}

To create angular module we need to import

NgModule

,

BrowserModule

and our components that we have created. All the components must be configured in

declarations

metadata of

@NgModule

decorator. The main component which will start other sub component must be configured in

bootstrap

metadata of

@NgModule

decorator.

Create Main TS File

The syntax for module bootstrap is as follows.

platformBrowserDynamic
().
bootstrapModule
(
AppModule
);

Now find our main TS file.

main.ts

import
{
platformBrowserDynamic
}
from
'@angular/platform-browser-dynamic'
;
import
{
AppModule
}
from
'./module'
;
const
 platform 
=
 platformBrowserDynamic
();

platform
.
bootstrapModule
(
AppModule
);

Here we will configure our module that is

AppModule

.

Create index.html

Find

index.html

used in the example.

index.html

<
html
>
<
head
>
<
title
>
Angular 2 Demo
<
/title
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1"
>
<
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
>
<
!-- Configure SystemJS --
>
<
script
src
=
"systemjs.config.js"
>
<
/script
>
<
script
>
System
.
import
(
'myApp'
).
catch
(
function
(
err
){
 console
.
error
(
err
);
});
<
/script
>
<
/head
>
<
body
>
<
msg-app
>
Please Wait...
<
/msg-app
>
<
/body
>
<
/html
>

Now we will conclude here how the angular application will run.

1.

When we run

npm start

command from root directory of the project using command prompt, our typescript files will be compiled in

.js

and

.js.map

files inside

app

folder as follows.

app
.
component
.
js
app
.
component
.
js
.
map
main
.
js
main
.
js
.
map

module
.
js

module
.
js
.
map

2.

Start point is

index.html

located in root directory. To run application we will access

index.html

. This page will execute the following script.

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

3.

Then

main.js

written in

systemjs.config.js

will be imported.

myApp
:
{

     main
:
'./main.js'
,

     defaultExtension
:
'js'
}

4.

Now the component element

<

msg-app

>

in

index.html

will execute.

5.

The

<

msg-app

>

component element will be replaced by component HTML template that is

app.component.html

.

6.

In angular project development with TypeScript, we may face two types of errors.

a. Compile time error

: We face compile time error when we are compiling our project using

npm start

command. If there is any syntax error in typescript file, we will get compile time error displayed in command prompt. We need to look into error and fix it.

b. Runtime error

: If project is compiled successfully and when we run the application, then we need to look into browser console for any error. The error could be because of null or undefined values or because of any file path not found. We need to look into error and fix it. Such types of errors are called runtime error.

Run Application

Find the steps to run the example.

  1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.

  2. Download the source code using download link given below in the example.

  3. Go to the root folder of the project using command prompt and run

npm install

command.

  1. Now run

npm start

command.

  1. Now run index.html file. Find the print screen of the output.

http://www.concretepage.com/angular-2/getting-started-with-angular-2-using-typescript-step-by-step-example

results matching ""

    No results matching ""