Getting Started with Angular 2 - Part 1 (Hello World!)

I am really exciting to get start developing web applications with Angular 2 because almost everything has changed in migration from Angular 1.x to Angular 2 even though the core philosophy of Angular remains the same. I couldn't wait to see the new directives and components changed in Angular 2. However, first things first, I kept clam and make myself familiar with TypeScript and Angular core concepts first. You can take a look at TypeScript for Angular 2: Part 1, Part 2, Part 3 and Part 4, if you want to. For me, it's about time to get started with Angular 2.

We have seen enough advantages of using TypeScript in Angular 2 development. So, I will use TypeScript through out all my Angular 2 development posts even though ECMAScript 5 is still available to use.

Let's say Hello world! with Angular 2.

Angular team introduced its new version of Angularjs along with everything we need to develop our web apps. From setting up the development environment to developer cookbook, they are all there at Angular 2 official website (https://angular.io). However, according to the nature of official documentation, you will see a long list of unfamiliar syntaxes and explanations. So, I will guide you through a much simpler path of learning Angular 2 in this post.

Set up Angular 2 development environment

Before we start developing our Hello world! app, we need to set up our development environment that is responsible especially for configuring node modules dependencies, setting TypeScript's compiler options and syntaxes, and defining npm scripts to handle common development tasks.

You need node and npm on your machine to start this tutorial. You can read instructions how to install node.js, if not already on your machine.

Create a new project folder

First create a folder where appropriate on your machine to contain our project files with the following command in Terminal. I used to create my web projects under a folder called Sites located in Mac OS X home directory.

mkdir angular2-helloworld && cd angular2-helloworld

Configure guidance for TypeScript compiler

Add a new file named tsconfig.json, which guides the TypeScript compiler, to the project folder and paste the following:

{
  "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"
  ]
}

You can see the main purpose of tsconfig.json file even if you dont understand how each command works exactly at this stage.

Define ambient type definitions

After tsconfig.json, add a typings.json file to the root of project folder and paste the following code. I already post about this at TypeScript for Angular 2 - Part 3 (Amazing TypeScript Features) post. This typings.json file allows TypeScript compiler to recognise external type definitions of the existing JavaScript libraries.

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b"
  }
}

Dont worry if you are not understanding every single line of these two files. We will catch up them later and we have to learn slowly because there are so much things to learn left about Angular 2.

Add node dependencies and devDependencies

Create a new file called package.json, which is already familiar with us, and copy/paste the following content:

{
  "name": "angular2-helloworld",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"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.15",
    "systemjs": "0.19.26",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.10"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^0.7.12"
  }
}

As you can see, there are a few dependencies node modules and npm scripts commands. However, the only npm commands that we will use in Hello world! tutorial are npm install and npm start, which have their own follow up commands, such as compiling TypeScript and running lite-server.

Install packages

Enter the following npm command in Terminal (command window in Windows) to install all packages described above to our project.

npm install

When you see console messages ending with npm ERR! with red colour, it means that the installation of dependencies modules fails. When you see yellow colour npm WARN! messages, please ignore them and you can know the installation is completed.

npm ERR! cb() never called!

This is the only one likelihood error that you may encounter in this node modules installation. If you dont have this error, please skip this section.

Solution: Install the latest stable version of Node.js by using following commands:

sudo npm cache clean -f  
sudo npm install -g n  
sudo n stable  

Explanation: Although this error only occurs to old version of Node, I encounter this error at v5.9.1, which is the most recent Node version. However, this problem is fixed when I update my Node to v5.10.1.

Now, we are all done setting up development environment. Let's write some code.

The first Angular 2 component written in TypeScript

This is the code that I want to write most since I have learnt Angular 2. So, why hesitate now? Let's create our first Angular 2 component in TypeScript.

Make a folder called app inside our project folder. Then create a app.component.ts file inside that app folder and copy/paste with the following snippet:

// angular2-helloworld/app/app.component.ts

import { Component } from 'angular2/core';

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html'
})
export class AppComponent {  
  target: string;
     constructor() {
       this.target = 'world';
     }
}

What we create is a root component, called AppComponent in this snippet, of our Angular 2 hello world app.

We need to import the Angular Component function from the main Angular library module as we are going to define a component.

An Angular app is built with basic building blocks called Components and every app has at least one root component, called AppComponent in our app. @Component is just a function but it is kind of decorator function that takes a metadata object that tells Angular how to create and use this component. When we want to define a decorator function to a component class, we have to declare the function by prefixing with @ syntax before that class.

In our component function, we added two fields to our metadata object, a selector and a templateUrl. The selector is just a simple CSS selector for an HTML element that represents the component, which has the value of my-app. This mean Angular will display the created instance of our AppComponent wherever it encounters a my-app element in the host HTML. The templateUrl specifies the path to our component's companion template written in HTML.

Beware when defining the path for templateUrl. Although the two files will be in same folder app, a relative path ./app.html cannot be used. We have to specify the path all the way back to the application root as Angular doesn't support module-relative paths.

After that, a component class is defined to controls the appearance and behaviour of a view through its template. In order to able to import from another module, we finally export AppComponent class, declare a string variable called target and put some value to this in the constructor.

Add the appComponent template

Then we will add app.html inside the app folder as a companion template for our AppComponent and copy/paste the following line:

<h1>Hello {{target}}!</h1>

What we are doing is very simple. We put our declared variable target inside double curly brackets like we always do.

Bootstrapping our app

After we created our root component AppComponent along with its template, we need to tell Angular to load it. Create a new file called main.ts also inside app folder with the following content:

// angular2-helloworld/app/main.ts

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

bootstrap(AppComponent);  

We import bootstrap function first from angular2/platform/browser and AppComponent from app.component.ts file that contained our app root component. There are more than one way to bootstrap Angular 2 app and we will learn that at a later time.

Although we can combine those two tiny code files: app.compontent.ts and main.ts, it is a good practice to follow single responsibility principle, which means gathering together only the things that change for the same reasons. You can also take a look at a complete set of best practices at Angular 2 Style Guide.

Add the main web page index.html

Add an index.html file in our project root folder and paste the following:

<html>  
  <head>
    <title>Getting Started with Angular 2</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 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/es6/dev/src/testing/shims_for_IE.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/main')
            .then(null, console.error.bind(console));
    </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>  

In this HTML index page, we first load Internet Explorer polyfills to enable ES2015 promises and dynamic module loading features working on IE. After that, we load the polyfills for Angular 2 which is required by the framework including ES2015 shim, zone.js, and others. Then the SystemJS library, which load application and library modules, and Reactive Extensions RxJS library, which is used by Angular's core that allows us to empower the reactive programming paradigm, are loaded. Finally, the web development version of Angular 2 itself is loaded.

The second thing we need to pay attention in this page is SystemJS configuration, which loads our Angular 2 application and library modules. In System.config function, the packages node tells SystemJS to define into a polyfills module with a default extensions, js, when it encounters a module from the app/ folder. Remember the main.ts file that contains bootstrap function, in our app folder? That main file (main.js after compiling main.ts) is imported here by System.import function, which also catch and log launch errors to the console.

Finally, <my-app> became the root component of our app that is selected by @Component selector in AppComponent metadata. Our application will load between those tags when Angular calls the bootstrap function in main.ts.

Run our first Angular 2 App

To run our first Angular 2 Hello world! app, we need a local host and blah blah blah....

No, all we have to do here is a single following npm command from your project root folder.

npm start

This command will do compiling TypeScript in watch mode and running a static server called lite-server in a browser in browserSync mode in parallel. All the changes made in to our Angular 2 application will reflect instantly in browser.

Congratulations

You have successfully developed your first Angular 2 app. Let's review what do we learn from this tutorial. We have learnt how to setting up TypeScript, configuring package.json, defining the root component along with its template, bootstrapping an app and configuring SystemJS and references to JavaScript libraries, which are the most fundamental things to develop Angular 2 application.

However, like I said above, there is still much things ahead to learn about Angular 2, such as using its built-in directives, defining our own directives, understanding components' inputs and outputs and their life cycle, so on... See you soon at Getting Started with Angular 2 - Part 2 (Using Built-in Directives).

Thank you for reading this post and your sharing makes my day if you enjoy this post. Cheers.

Nay Win Myint

Founder and CEO of Pancasikha Music Streaming Provider, JavaScript full-stack and Android developer and Graphic designer.

Rangoon, Myanmar