Sunday 19 June 2016

How to start with Angular 2

This post is outdated now

Here we will discuss about how we can create a simple app using angular js 2. So first up all the question is why angular js 2?

Angular js 1 is basically developed for google developers for their internal use and more over it is developed for UI designing purpose and later they extended many features like two way data binding etc. Now Angular js 1 is widely used by developers. Recent past some architectures and developers points about performance issues and angular core team finally come up with a new version of Angular and it is Angular js 2. Which is well structured and it offers a very good performance.

There is a lot of difference between angular one and two. Angular two is supporting JavaScript ES6 which is not yet supported by latest browsers however you can use current JavaScript ES5 with angular 2, but you may not be able to enjoy all features of angular 2 in this case.

So the best option is to use Angular two with typescript. In this case you need to compile the files before rendering into the browser as browser is not yet supporting ES6. But in coming future it should be supported and you can use angular 2 with JavaScript ES6 directly.

In this article I am going to explain how we can start a simple application using Angular 2 + Typescript. Typescript is superscript of JavaScript.

Before starting be ready with following things.

1. Visual Studio Code [ https://code.visualstudio.com/ ]
(As this editor supporting typescript so that you can enjoy coding)

2. NodeJS [ https://nodejs.org/en/download/current/ ]

Create folder structure similar like below screen shot

 

package.json


  {
  "name": "angular2_app",
  "version": "1.0.0",
  "description": "My first Angular 2",
  "main": "index.js",
  "scripts": {
    "start": "tsc && concurrent \"npm run tsc:w\" \"npm run lite\" ",
    "lite" : "lite-server",
    "tsc": "tsc",
    "tsc:w" : "tsc -w",
    "typings" : "typings"
  },
  "keywords": [
    "angular2",
    "node",
    "typescript",
    "javascript",
    "html5"
  ],
  "dependencies": {
    "angular2": "2.0.0-beta.17",
    "es6-shim": "0.35.1",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "0.6.12",
    "systemjs":"0.19.31"
  },
  "devDependencies": {
    "concurrently" : "1.0.0",
    "lite-server" : "1.3.1",
    "typescript":"1.7.3"
  },
  "author": "Prashobh",
  "license": "ISC"
}

It contains all the dependencies. The script sections details are used for typescript for compiling purpose.Once you add package.json, go to command prompt and run "npm install" or you can open the folder and do "shift + right" click you will find an option "open command window here" ,click that and type "npm install". You can add other dependencies as well (eg:bootsrtap) then you can just type "npm update". You can see a folder "node-modules" is created with all the files.

Index.html


<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<!--Lib includes-->
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<!--App includes-->
<script type="text/javascript">
  System.config({
 packages: {
  app : {
   format: 'register', 
   defaultExtension: 'js'
  }
 }
   });
 System.import('app/boot').then(
  console.log.bind(console),
  console.error.bind(console)
 );
</script>
<title>MY first angular 2 app</title>
 </head>
   <body class="container">
     <sample-list></sample-list>
    </body>
</html>



tsconfig.json


{
    "compilerOptions": {
        "target": "es6",
        "module":"system",
        "moduleResolution":"node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
    },
    "exclude":["node_modules"]
}



Under App I am creating some files, please see the below screenshot

sample-list.html


<h2>{{title}}</h2>
<div>
 <ul>
  <li *ngFor="let i of items">
   <p>{{i.name}}</p>
   <p>{{i.des}}</p>
   <p>{{i.exp}}</p>
  </li>
 </ul>
</div>


sampleComponent.ts

sampleComponent.ts is typescript file. I added JSON file inside the constructor itself for now, ideally it should be from service file, I am not going to explain those in this post.


import {Component} from 'angular2/core'

@Component({
    selector: 'sample-list',
    templateUrl: 'app/sample-list.html',
})
export class sampleComponent {
    title: string;
    items: any[];
    constructor() {
        this.title = "My first Angular 2 Application";
        this.items = [{
            name:'Prashobh',
            des:'SSE',
            exp:'10',
        },
        {
            name:'Abraham',
            des:'PM',
            exp:'15',
        },
        {
            name:'Anil',
            des:'SE',
            exp:'2',
        }]
    }
}


Boot.ts

In angular 2 we need to initialize the things rather than browser taking the control.


import { bootstrap } from 'angular2/platform/browser'
import { sampleComponent } from './sampleComponent'

bootstrap(sampleComponent)
    .then(
 a => { 
  console.log('--Bootstrap success!')
  console.log('--Catalog App is ready!')                    
 },
 err => console.error(err)
);


Now open command prompt and type "npm start". You can see your first Angular 2 app.

If you are getting any error check typo mistake and also try to debug in chrome.

The above demo is a kind of hello word application just to start with angular js 2. I will be writing more about on angular js 2 and things like setting a single page application. If you are interested bookmark this page.

Related Post

1. ng-repeat in angular js 2

2. Angular 2 filter using pipe concept

3. ng-click in angular js 2

2 comments :