Thursday, September 29, 2016

Getting Started with Angular 2 using TypeScript

In this article I'm trying to show how you can develop a start-up project in Angular 2.


What you will learn ?

After completing this post, you will be able to do the following things.
  • You will be able to setup your environment to develop Angular js 2 with typescript application.
  • You will be able to create an application in angular js 2
  • Basic knowledge on Type Scripts and its transpiler.
  • Basic knowledge Node Package Manager tool.
  • Real-time application development. Changes automatically reflect the UI without refreshing the browser.

Create a new project folder:

Open the command prompt and run these two commands.

mkdir hello-world-angular-2
cd hello-world-angular-2

Node Js:

If you don't have node on your machine download from Node JS and install it on your machine.
It's pretty easy and straightforward to install.
With node we get a tool called npm or node package manager which we use for managing dependencies of our application.

TypeScript:

So once you install node, open up command prompt on windows and run the following command

npm install -g typescript


which will install the typescript globally in your computer.

Code Editor:

You need a code editor which support typescript, In this tutorial I'm using visual studio code editor which is beutiful, lightweight and cross-platform editor from Microsoft. It's free and open source awesome editor. You can also download it from here. You can use any other code editor you like.

Add the libraries what we need in our project:

Add a package.json file to the project folder and copy/paste the following:

package.json

 {
  "name": "hello-world-angular2",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  },  
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.7",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.7.5"
  }
}
           
package.json is a standard node package configuration file.
Here we declared all dependencies of our application
You will get details about package.json from this link package.json

In this file we add a script line: "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
Here we run the two command concurrently.
"npm run tsc:w" => Run the typescript compiler in watch mode.
"npm run lite" => Run the light web server.

With typescript compiler running in the watch mode we can modify and save a type script file and then the typescript compiler will automatically generate a javascript and a javascript map file in the same folder.
The javascript file actually be loaded in browser.

Now run the following command from the command prompt:

npm install

npm will look at our package.json file and download all dependencies, once all dependencies are installed you will see a new folder name node_modules in your project folder.
Scary error messages in red may appear during install. Ignore them.
Add a tsconfig.json file to the project folder and copy/paste the following:

tsconfig.json

 {
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}
           
tsconfig.json is the configuration file for typescript compiler, So it uses this configuration file to determine how to compile or more accurately transpile typescript files into javascript files.
If you want to learn more details about this configuration file please go to ts configuration documentation files:
1. tsconfig-json
2. tsconfig in angualr
Add a typings.json file to the project folder and copy/paste the following:

typings.json

 {
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
  }
}
           
typings.json another configuration file. when we use external javascript files in typescript we need to import what we called a typescript definition file this type definition file gives us static type checking and intelligence for that javascript library.
If you want to learn more details about this configuration file please go to ts configuration documentation files:
1. typings-json
2. typings-config in angualr

Create an application source sub-folder:

We like to keep our application code in a sub-folder off the root called app/. Execute the following command in the console window.
mkdir app
cd app

Add the component file:

Now add a file named app.component.ts and paste the following lines:

app/app.component.ts

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>Hi, {{name}} <br /> Wellcome to the angular 2 application development world.'
})
export class AppComponent {
    name: string = "Emon Khan";
}
           
app.component.ts is the root component in our application.

Add the boot file:

Now add a file named boot.ts and paste the following lines:

app/boot.ts

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'

bootstrap(AppComponent);
           
boot.ts is our main or starting module of our application.

Add the index.html file:

Now add a file named index.html and paste the following lines:

index.html

<html>
<head>
  <title>Hello World Angular 2</title>

  <!-- 1. Load libraries -->
  <!-- IE required polyfills, in this exact order -->
  <script src="node_modules/es6-shim/es6-shim.min.js"></script>
  <script src="node_modules/systemjs/dist/system-polyfills.js"></script>

  <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <script src="node_modules/rxjs/bundles/Rx.js"></script>
  <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

  <!-- 2. Configure SystemJS -->
  <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>

</head>

<!-- 3. Display the application -->

<body>
    <my-app></my-app>
</body>

</html>
           

Now your file stucture should be like this:


Run the application:

now run the following command from the project folder localtion:

npm start


Now our typescript compiler running in watch mode and our light web server started. This also launches default web browser and you will
"Hi, Emon Khan
Wellcome to the angular 2 application development world." text in the browser.

Now open the app.component.ts and make some changes in template and you will see the changes in the browser without loading the browser. That's cool!!!

1 comment: