Angular 2 – Hello World App – Typescript

Important Note: The post has been updated to RC 1

Hi guys. I’ve been working with Angular 2 for the past week, so thought I must share whatever I’ve learned. I’ll be writing a series of blog posts on Angular 2. What better way to start the series than to do an hello world app.. 😛 Let’s get started.

Before we start, make sure you have node installed. Firstly, we’ll try to get the app up and running. Then we’ll go through the files one by one to understand what they do.

Create a new folder named angular-hello-world. This will act as our application’s root folder. Create four files inside it: typings.json, tsconfig.json, systemjs.config.js and package.json

Copy the following contents into their respective files.

package.json
tsconfig.json
typings.json
systemjs.config.js


Navigate to the angular-hello-world folder in the terminal and type the following command:

$ npm install

This will install angular and all the other required libraries. You must now be able to see a new folder named node-modules. Inside that you will see a folder named @angular among other libraries.

Application specific code

Create a folder named app inside the angular-hello-world folder. Now create two files named app.component.ts and main.ts inside it.

Copy the contents into their respective files:

main.ts
app.component.ts


Create a file index.html in the angular-hello-world folder and copy the following:

index.html


Open the terminal or command prompt and type the following command:

$ npm start

You should see your browser fire up and then display:

hello, world

in the rendered page.

TADA!!! You have your hello world Angular app up and running. Now let us understand what the various files do. We’ll start with the Angular files.

app.component.ts

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

@Component({
  selector : 'my-app',
  template : '<h1>Hello, World!!!</h1>' 
})

export class AppComponent {}

Everything in Angular 2 is made up of components, which are the basic building blocks. A component is made of up of a class and a view that is controlled by that class. In the above file, we declare an AppComponent, that will act as the root component of our hello world application.

Angular 2 is modular in nature, which means everything is defined as modules and to use a module we must import it. Here, we import Component module from the angular core library to use it.

Components are defined using @Component decorator. The decorator takes in a metadata config object. Angular uses this object to understand how to create, configure and use this component.

The component is identified by Angular using the selector metadata value, which is a CSS selector. When parsing the HTML, when angular comes across the my-app tag, it instantiates AppComponent with it’s corresponding view. The view of the component is identified by the template metadata. Here, we have simply defined it to be an h1 element with “hello, world” as text.

Finally we make this component class exportable so that we can import it elsewhere.

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';

bootstrap(AppComponent);

All angular apps start with the bootstrapping process, which basically is where angular starts taking control of an application. Bootstrapping typically begins with the root component.

We import bootstrap module and also our root component, AppComponent. We pass the AppComponent as parameter to the bootstrap function.

The reason for using a separate file for the bootstrapping process is that, it allows AppComponent to be independent, so that if need arises for it to be tested, we can do so without any difficulties.

index.html

<html>
 <head>
 <title>Angular 2 Hello World</title>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="styles.css">
 <!-- 1. Load libraries -->
 <!-- Polyfill(s) for older browsers -->
 <script src="node_modules/es6-shim/es6-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>
 <!-- 2. Configure SystemJS -->
 <script src="systemjs.config.js">< /script>
 <script>
 System.import('app').catch(function(err){ console.error(err); });
 < /script>
 </head>
 <!-- 3. Display the application -->
 <body>
 <my-app>Loading...</my-app>
 </body>
</html>

Inside, the body tag, we have declared the my-app tag, which we defined as the selector for the AppComponent. This is where Angular will instantiate our application.

As mentioned earlier, we work with modules throughout our application and hence we need a module loader. We have used SystemJS and also have configured it in index.html.

System.import('app')
            .then(null, console.error.bind(console));

This line tells SystemJS to use app folder as the entry point to launch our application. We also bind our console to show errors if they occur.

systemjs.config.js

This file is used to configure the SystemJS module loader.

var map = {
 'app': 'app', // 'dist',
 'rxjs': 'node_modules/rxjs',
 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
 '@angular': 'node_modules/@angular'
 };

These lines tell SystemJS how to respond to requests to the app folder among others.

var packages = {
 'app': { main: 'main.js', defaultExtension: 'js' },
 'rxjs': { defaultExtension: 'js' },
 'angular2-in-memory-web-api': { defaultExtension: 'js' },
 };

Here, the line in bold tells that main.js is the entry point in the app folder and that the default extension for the files is js as all .ts files are transpiled to .js files.

Learn more about configuring SystemJS here.

We also import a host of poly fills and supporting libraries at the top. Though we might not use some of them now, we might require them later. So we just add them.

Other Files

package.json

We install all our required dependencies through npm. We need a package.json file to declare our dependencies and install them. We install a package lite-server which will act as our dev server.
You might remember, we used the command npm start to run our application. This is defined inside scripts.

"scripts": {
    "start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

As you can see, start command is defined to concurrently run both the typescript compiler and the lite server. Also note that the typescript compiler is configured with the w flag, which is the flag for watch. This means whenever you make a change to any of the application files, the typescript compiler will run and the server will automatically reload the page to reflect the changes.

typings.json

Typescript by default does not understand the libraries that extend JS, so it will result in compilation errors. So we let typescript know of these libraries using this file. We have declared the testing framework jasmine and es6-shim which enables legacy browsers understand ES6.

tsconfig.json

This file declares a list of typescript compiler options. We can configure things like whether we want to add/remove comments from the compiled code, whether the compiled code should auto-detect variable types or not. You can learn about all the compiler options here.

That’s it for this tutorial guys. You have created your very own hello world application in less than 5 minutes..(WooHoo..:D) and a bit more time to understand it though..:P. Hope this post helped you to get started with Angular 2. See you in the next one guys..Peace..:)

Advertisements

2 thoughts on “Angular 2 – Hello World App – Typescript

    • Not sure what your question is here, but since main.ts and app.component.ts are in the same folder and we are importing AppComponent in main.ts, I’ve used
      import {AppComponent} from ‘./app.component’
      to import AppComponent into main. Note ‘./’ indicates the current directory.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s