Your Definitive Guide for AngularJS 2.0

Your Definitive Guide for AngularJS 2.0
COMMENTS ()
Tweet

As a developer, I’m always excited to write about cutting edge new technologies and platforms that have just been introduced in the software development industry. One of these recently introduced technologies is Angular JS v2.0, which based on the industry’s feedback so far, seems to be a very promising platform.

In this post, we’re going to look at Angular JS 2.0 in detail, which will help those of you who are new to Angular JS, get started with development on this new platform. For those of you who already know what’s different in Angular JS 2.0, or if you can’t wait to write your first Angular JS 2.0 app, then you can just skip the pre-requisites section and follow the steps I’ve described afterwards.

What’s different in Angular JS v2

The one stand-out feature in Angular JS 2.0 which is also common in ReactJS, is that they both have embraced the new web-components development architecture. What this basically means is that you can now create independent, plug and play web components that can be plugged into any website that has the same technology stack of that web component.

The other prominent change in Angular JS 2.0 is that its primary development language is TypeScript. TypeScript belongs to Microsoft, it’s actually a superset of 2015’s JavaScript (or ECMAScript6/ES6) and offers some very cool features. I would recommend that you check out TypeScript in more detail after going through this tutorial.

Folks that try interrelate Angular JS v1 and Angular JS 2.0 are only confusing themselves as well as others, since Angular JS and Angular JS 2.0 are vastly different and should be treated as two separate frameworks. The major difference being the development methodology they offer. Angular JS 2.0 uses the web-components concept of web application development, whereas Angular JS v1 uses controllers, which are absent in Angular JS 2.0.

Background

JavaScript development has evolved so much that you have to be on your toes all the time in order to keep up with the latest JavaScript frameworks and toolsets that are introduced every month (if not every day). Due to these rapid changes, there are many things you need to learn as pre-requisites, before you can start developing in a particular framework. This post on Angular JS 2.0 will help you get started with development on Angular JS v2.

Pre-requisites

The pre-requisites for this tutorial include the following:

  • NodeJS installation
  • IDE or Text Editor
  • Motivation

Let’s get started

Firstly create a folder where you’ll save this application. Next, open the command-line tool in the created folder and input the following command:

$ npm init
I’ll tell you in a bit what exactly the above command does, but for now just go with the flow. So, after the pervious command you should run the following command which will create a package.json file
$ npm install -g bower
Next, execute this command:
$ bower init

This will create a bower.json file in this folder. Edit this file in the text editor and add a dependencies node (if it’s not there already) or if it is, just replace it with the following code.

"dependencies": {
  "bootstrap.min": "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css",
  "es6-shim.min": "https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js",
  "system-polyfills": "https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.16/system-polyfills.js",
  "system": "https://code.angularjs.org/tools/system.js",
  "typescript": "https://code.angularjs.org/tools/typescript.js",
  "angular2-polyfills": "https://code.angularjs.org/2.0.0-beta.7/angular2-polyfills.js",
  "Rx": "https://code.angularjs.org/2.0.0-beta.7/Rx.js",
  "angular2.dev": "https://code.angularjs.org/2.0.0-beta.7/angular2.dev.js"

Alternatively, you can also use the bower install command (below) to add the same.


$ bower install --save https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.16/system-polyfills.js https://code.angularjs.org/tools/system.js https://code.angularjs.org/tools/typescript.js https://code.angularjs.org/2.0.0-beta.7/angular2-polyfills.js https://code.angularjs.org/2.0.0-beta.7/Rx.js https://code.angularjs.org/2.0.0-beta.7/angular2.dev.js

These are actually the libraries you’ll need to continue with the development. Don’t worry if you don’t know about them, just consider them as commands and I’ll tell you at the end of this post about what they are and what they do.
Now, create a file named config.js in the folder and write the following code in that file

System.config({
  baseURL: "/",
  transpiler: 'typescript',
  typescriptOptions: { emitDecoratorMetadata: true },
  packages: {'app': {defaultExtension: 'ts'}},
  paths: {
    "packages:*": "bower_components/*"
  }
});

 

Next, create an index.html file with a blank HTML body and add the following code in the head tag.

<!-- load in this exact order -->

<link href="bower_components/bootstrap/index.css" rel="stylesheet">

<script src="bower_components/es6-shim.min/index.js" charset="utf-8"></script>
<script src="bower_components/system-polyfills/index.js" charset="utf-8"></script>
<script src="bower_components/system/index.js" charset="utf-8"></script>
<script src="bower_components/typescript/index.js" charset="utf-8"></script>
<script src="bower_components/angular2-polyfills/index.js" charset="utf-8"></script>
<script src="bower_components/rx/index.js" charset="utf-8"></script>
<script src="bower_components/angular2.dev/index.js" charset="utf-8"></script>

<script src="config.js" charset="utf-8"></script>

 

After this, add a script tag in the head tag, as shown below.

<script>
  var errorLogger = (console.error || console.log).bind(console);
  System.import('app/main')
        .then(null, errorLogger);
</script>

 

Now, add the following code in the body of the index.html file.

<div class="container">
  <div class="row">
    <div class="col-xs-6 col-md-4"></div>
    <div class="col-xs-6 col-md-4" style="text-align: center;">
      <b>Getting Started with Angular v2</b>
    </div>
    <div class="col-xs-6 col-md-4"></div>
  </div>
  <br/>
  <div class="row">
    <div class="col-xs-6 col-md-4"></div>
    <div class="col-xs-6 col-md-4">
      <get-started style="display: block">Loading...</get-started>
    </div>
    <div class="col-xs-6 col-md-4"></div>
  </div>
</div>

 

If you look closely at the script above, you’ll notice that there is get-started tag mentioned in there. This is where your first Angular JS 2.0 app will be placing its code, and yes, it is a Web-Component.

Now, create a folder named app and create a file within that named main.ts (ts is a widely used file-extension for TypeScript), and add the following code at the top, to ensure stricter code validation within the browser.

“use strict”;

Now, import the Angular libraries using the code snippet below (typescript syntax)

import {
  Component,
  View
} from "angular2/core";

import {bootstrap} from "angular2/platform/browser";

 

This will import a few things from Angular’s core framework, and a bootstrap method from Angular’s browser helper, which will eventually load your app in the browser.

We are basically creating an application that displays a table of people along with their roles in an organization. Now, write this code in the file.

/* Container class for Person Role data */
class PersonRole {
  name: string;
  role: string;
  constructor(name, role){
    this.name = name;
    this.role = role;
  }
}

 

Now comes the fun part, where you are actually writing something in Angular JS 2.0 (typescript syntax)

/* Component Decorator*/
@Component({
  /* This is the tag-name which will be used in HTML like <get-started></get-started> */
  selector: 'get-started'
})
/* View Decorator */
@View({
  /* This is the template of the view, you may see ngFor here to iterate the items */
  template: `
    <div>
      <div class="row" style="background-color: #0b5394; color: #fff;">
        <div class="col-xs-6 col-md-4">Name</div>
        <div class="col-xs-12 col-md-8">Role</div>
      </div>
      <div class="row" *ngFor="#personRole of personRoles" style="border-bottom: 1px solid #dadada;">
        <div class="col-xs-6 col-md-4">{{personRole.name}}</div>
        <div class="col-xs-12 col-md-8">{{personRole.role}}</div>
      </div>
    </div>
  `
})
class GetStartedApp {
  /* The state of this component (used by view) */
  personRoles: PersonRole[];

  /*
    Simple plain construtor to start-up the things
  */
  constructor(){
    this.personRoles = [];
    this._loadNextRole();  /* Starts loading person-roles */
  }

  /*
    This is the magic method which will pop a PersonRole out of the PersonRole Array
    and push it to our app's personRoles array. This will simulate the behavior of what happens when
    the state of a component gets changed
  */
  private _loadNextRole() {
    let personRoles = this._getPersonRoles(),
      self = this,
      interval;

    interval = window.setInterval(function () {
      if (personRoles.length === 0) {
        window.clearInterval(interval);
      }
      self.personRoles.push(personRoles.pop());
    }, 1000);
  }
  /*
    Get's an array of person-roles from the database
    Actually not database, but for the simplicity sake and since this is the getting-started app
    consider that this method fetches it from database and returns an array of PersonRole objects.
  */
  private _getPersonRoles() {
    return [
      new PersonRole("Shehzeen Huda", "Software Engineer"),
      new PersonRole("Syeda Sidrah", "Software Engineer"),
      new PersonRole("Mohammad Hammad", "Software Engineer"),
      new PersonRole("Ammar Hasan", "Software Engineer"),
      new PersonRole("Fahad bin Saeed", "UI Engineer"),
      new PersonRole("Abdul Sami", "Sofware Architect"),
      new PersonRole("Mufaddal Ismail", "Project Manager")
    ]
  }
}

 

The code above may look like it’ got strange syntax but it’s not hard to grasp. If you just think over the syntax, it’s basically TypeScript on your desktop. @Component and @View are actually decorators (which follow decorator patterns), that actually decorate the GetStartedApp class as a class which has an Angular View (because of the View decorator) and an Angular Component (becuase of Component decorator).

First, let’s inspect the Component decorator. We are basically providing a selector get-started here, so that when the app runs it will find the get-started tag and put all the logic of GetStartedApp within it. Then we have View, which is simple plain html (this could be a URL to an external template file also), that has an ngFor attribute. What ngFor does is that it iterates the personRoles array of GetStartedApp and writes the name of each personRole in the html

<div class="col-xs-6 col-md-4">{{personRole.name}}</div>
<div class="col-xs-12 col-md-8">{{personRole.role}}</div>

 

Then there is the GetStartedApp class, which houses a few methods to load the data and update the personRoles array.

Coming back to the tutorial, in the main.ts file at the very bottom, write the following to start your app.

/* This will start the app */
bootstrap(GetStartedApp);

At this moment, your code’s directory structure will look like this.

|-- angular2-ts-get-started
    |-- bower.json
    |-- config.js
    |-- index.html
    |-- package.json
    |-- app
        |-- main.ts

 

Now that you’re done with all the cool stuff, you have one last thing to do, and that is to create a web-server which will host your very first Angular JS 2.0 app. So, write the following command to install a simple NodeJs Server.

$ npm install -g http-server

Now, start this server using the following command (make sure you are in your code folder when you do so). This will also open the browser and load your Angular JS 2.0 webpage at port 8080.

$ http-server –cors -o -p 8080

Alternatively, you can also add this in the scripts tag in the package.json file

“start”:“http-server –cors -o -p 8080”

Doing so will enable you to run the server using this simple command

$ npm start

And that’s it. Congratulations, you have just created and used your first Angular JS 2.0 app!

 

Libraries used in this Tutorial

  • Bootstrap: A CSS framework to do the make-up of this app.
  • Es6-shim: This is a shim which enables us to use JavaScript 2015 (ES6) features (this is also a requirement for SystemJs)
  • System-polyfills: This is a polyfill which enables the support for System.import.
  • Systemjs: This is a library which can load modules and files at the runtime (this library is very powerful and can be used for different types of module definitions).
  • Typescript: A library to transpile typescript to regular javascript on the go.
  • Angular2-polyfills: This polyfill enables all the extended features used by Angular v2 which are not yet supported by browser’s javascript engine.
  • Rxjs: This library enables reactive programming used by Angular v2.
  • Angular2-dev: The main development library for Angular v2 framework.

Some Info about the cool things we’ve used

  • NPM: This is the NodeJs package manager, a place from where we can import and use all the cool packages developed by the coolest developers.
  • Bower: Bower is a tool over NPM, which enables us to import and manage cool javascript frontend libraries in our applications.
  • Http Server: A very simple but an awesome http web server over NodeJs, which servers every thing and also supports cross origin requests.

Further study material

  • TypeScript
  • Decorator pattern

FAQS

  • What does npm init do? Answer: This command initializes NPM package management over the current directory, and adds a package.json file, which will manage the installed packages and other scripts.
  • Why did we use npm here? Answer: The purpose was that readers should start using NPM if the haven’t already used, because in near future of Angular development, they will likely be encountering NPM, so it’s good to start using now.
  • What does bower init do? Answer: This command initializes bower frontend package management over the current directory, and adds a bower.json file.
  • Why did we use bower in this example? Answer: Because this will enable the reader to get-used-to bower simultaneously with programming in Angular JS, also instead of using directly from CDN doesn’t work when network is not available.
  • What is the difference between bower and npm? Answer: The difference is that bower is a package of NPM for frontend. And hence bower uses NPM, also github and CDN repositories, and manage the use of frontend libraries.

In the next tutorial we will learn about Angular 2 Components.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812