LanguagesJavaScriptWriting My First AngularJS 2 App

Writing My First AngularJS 2 App

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

To set up our development environment, we start by installing the needed artifacts. Afterwards, we will create the project and, in the end, we will run it.

Let’s start!

Prerequisites

Before we write an AngularJS 2 application, we need to perform several prerequisites.

To start, we need to install Node.js (node and npm). You have to choose the Node.js distribution compatible with your operating system and install it locally by following the instructions provided on the Web site. Furthermore, we will suppose that you have successfully installed Node.js.

Now, let’s create the project folder. Choose a location on your computer and create a new folder named angular2. In this folder, we will place all the files of our application.

In the angular2 folder, we need to add three JSON files: one to guide the TypeScript compiler, one that identifies the missing TypeScript definition files, and one that defines the packages and scripts we need.

Guide TypeScript Compiler

The first one is named tsconfig.json. Its standard content should look like this:

{
   "compilerOptions": {
      // Specify ECMAScript target version
      "target": "ES5",
       // Specify module code generation
      "module": "system",
      // Specifies module resolution strategy
      "moduleResolution": "node",
      // Generates corresponding '.map' file
      "sourceMap": true,
      // Emit design-type metadata for decorated
      // declarations in source
      "emitDecoratorMetadata": true,
      // Enables experimental support for ES7 decorators
      "experimentalDecorators": true,
      // Do not emit comments to output
      "removeComments": false,
      // Warn on expressions and declarations with an
      // implied 'any' type
      "noImplicitAny": false,
      // Generates corresponding d.ts files
      "declaration": true
   },
   // Points folders and file to exclude
   "exclude": [
      "node_modules",
      "typings/main",
      "typings/main.d.ts"
   ]
}

The content of this file and the values may vary. But, to alter its content/values, you have to understand the meaning of each entry. A good start of learning TypeScript can be found in the official tutorial, but for a quick start, you can also try here. Or, you can directly try the the schema.

Identify the Missing TypeScript Definition Files

The second JSON file is also related to TypeScript. This is named typings.json and it should be located in thee angular2 folder. Its content identifies missing TypeScript definition files:

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

This file points to declaration files of type .d.ts. These files are needed when we are using external JS files or a host API. In our case, we identified two typings files: the d.ts file for es6-shim that brings ES2015/ES6 capabilities to our ES5 browsers and for the jasmine test framework. More details are available here.

Define the Packages and Scripts We Need

Finally, we add the package.json file in the angular2 folder. This file is used by npm to install the pointed artifacts. Basically, Angular2 relies on the npm package manager to install the libraries needed by the application. The starter-set of packages should be specified in the dependencies and devDependencies sections:

{
   // Name of the application's folder
   "name": "angular2",
   "version": "1.0.0",
   "scripts": {
      "start": "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.12",
      "systemjs": "0.19.24",
      "es6-shim": "^0.35.0",
      "reflect-metadata": "0.1.2",
      "rxjs": "5.0.0-beta.2",
      "zone.js": "0.6.6"
   },
   {
      "concurrently": "^2.0.0",
      "lite-server": "^2.1.0",
      "typescript": "^1.8.9",
      "typings":"^0.7.9"
   }
}

The complete documentation for package.json can be found here.

The npm Commands

Now, we can run the npm commands. The easiest way to obtain the desired result is to run the following command (from the command line, navigate in the angular2 folder and type the following command):

npm install

Angular1
Figure 1: Installing the npm package

Note: If you see some errors (in red), do not worry. The install typically recovers from these errors and finishes successfully.

As you can see in Figure 1, the result of running the npm install command was two new folders: node_modules and typings. You can have a quick check to see what they contain.

Create the Application Folder

The application folder is named app and it should be manually created and located in the project folder, angular2.

Basically, at this point we have finished all the prerequisites and we can start developing the application.

Create the Application

Angular2 JS applications are component-driven.

Create the Component File

Typically, each Angular2 component is mapped in a *.ts file.

At this point, we have finished all the prerequisites and we can start developing the application. Practically, we build an Angular2 JS application by creating and shaping components. These components act as the “bricks” of our application. It is mandatory to define at least one component, and for this we need to write a *.ts file. We will create an “Hello World!” example, so we can name our file app.helloworld.ts and place it in the /angular2/app sub-folder.

The app.helloworld.ts content will be:

1: import {Component} from 'angular2/core';
2:
3: @Component({
4:    selector: 'hello-world',
5:    template: '<h1>Hello World!</h1>'
6: })
7:
8: export class AppComponent {
9: }

Let’s dissect this code and see what it does (in Figure 2, you can see the AngularJS 2 terminology):

Angular2
Figure 2: Studying the code

Line 1: Angular2 JS is built in a modular fashion. This means that we can build our components by importing the right artifacts from the right modules in our component. Typically, you will import at least the Component artifact (decorator function) from the angular2/core module. This is needed to define a component.

Line 3: The Component is a decorator function that takes a metadata object. Via metadata, we shape the look and behavior of our component. The function is applied to a component by prefixing it with @.

Lines 4-5: These two lines represent the fields of our metadata object. Typically, these two fields will be contained by each component, but there are more optional fields, like directives, providers, or styles.

Line 4: The selector field is part of the metadata object. Basically, this field points to a CSS selector for an HTML element that represents the component. In our case, the element for this component is named hello-world. This element will be used in our HTML application, and AngularJS will instantiate our component for each occurrence of hello-world.

Line 5: The template field is also part of the metadata object. Via this field, we indicate the HTML markup that should be rendered for the hello-world occurrence. We will simply render the text Hello world!. The template can be very complex; it may contain data bindings, use other components, and so forth.

Lines 8-9: The AppComponent is the component class. Here is the business logic of our component. For example, here we can fire HTTP requests, invoke services, having routings, and so on. In our case, the component class is empty because we simply display a plain text. But, as you can see, even if it is a do-nothing class, we cannot skip its signature! The export meaning is pretty clear. We need to export our component so that we can import it elsewhere in our application.

Pointing to the Root Component

The root component acts as a “starting” point for our component tree.

In a real application, we will probably build a set of components that can interact with each other. But, each application must have a root component, so Angular2 will know what is the “starting” point in our application. The root component should be defined in a new file named main.ts in the /app folder, as shown below:

1: import {bootstrap}    from 'angular2/platform/browser';
2: import {AppComponent} from './app.helloworld';

3: bootstrap(AppComponent);

Line 1: On the first line, we import the bootstrap decorator function specific for applications that run in a Web browser. Most probably, your first Angular2 JS applications will use the Angular’s browser bootstrap function, because the Web browser is the easiest way to test your work. But, you have to know that Angular2 can load a component in a different environment (for example, on mobile devices). In such cases, the boostrap function must be loaded from specific libraries, not from angular2/platform/browser.

Line 2: We import our AppComponent function.

Line 3: We bootstrap/load our root component.

Note: You can merge these two .ts files into a single one, but this is the recommended and proper way to structure an Angular2 application.

Create Our Application’s Web Page

Now it is time to expose our component in a Web page.

We will name this page index.html and we will place it in the /angular2 folder. The content of this file is listed below:

<html>
   <head>
      <title>Angular 2 Hello World</title>
      <meta name="viewport" content="width=device-width,
         initial-scale=1">
      <link rel="stylesheet" href="styles.css">

      <!-- 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({
         {
            app: {
               format: 'register',
               defaultExtension: 'js'
            }
         }
      });
      System.import('app/main')
         .then(null, console.error.bind(console));
      </script>
   </head>

   <!-- 3. Display the application -->
   <body>
      <hello-world>Loading...</hello-world>
   </body>
</html>

Furthermore, let’s dissect this code.

As you can see, there are three main sections:

Section 1: Load Libraries

In this section, we need to add the JavaScript libraries needed to run our application. Depending on the application complexity, the number of these libraries may increase, but the minimum requirements involve:

IE requires polyfills to run an application that relies on ES2015 promises and dynamic module loading

<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>

Polyfills for Angular2

<script src="node_modules/angular2/bundles/
   angular2-polyfills.js"></script>

The SystemJS library for module loading

<script src="node_modules/systemjs/dist/
   system.src.js"></script>

Reactive Extensions RxJS library

<script src="node_modules/rxjs/bundles/
   Rx.js"></script>

Web development version of Angular 2 itself

<script src="node_modules/angular2/bundles/
   angular2.dev.js"></script>

Section 2: Configure SystemJS

To load the application and library modules, Angular2 JS supports different approaches. The recommended approach, but not mandatory, is based on SystemJS. If you are not open to learn more about SystemJS, you can follow this scaffold:

<script>
   System.config({
      packages: {
         app: {
            format: 'register',
            defaultExtension: 'js'
         }
      }
   });
   System.import('app/main')
      .then(null, console.error.bind(console));
</script>

Mainly, this code can be explained like this:

  • The packages node instructs SystemJS about the actions that should be accomplished in case of a request for a module from the app/ folder.
  • The packages: configuration tells SystemJS to default the extension to js, a JavaScript file.

The System.import call tells SystemJS to import the main file (main.js – after transpiling main.ts).

Section 3: Display the Application

Displaying the application to the client involves the “replacement” of the hello-world tag with the proper template. Remember that this tag is actually a selector in our component. When the bootstrap() function is called, Angular2 process our component and locates the metadata object that contains the hello-world selector. Furthermore, it locates the hello-world tags and loads our application between those tags. The element tag and the selector must have the same name.

Run the Application

At this moment, the development of our application is over. It is time to run it.

Running the application is very simple. From the project folder (angular2), run the following command:

npm start

This command will compile our application via two parallel node processes:

  • The TypeScript compiler in watch mode
  • The result of compilation will produce the following files in the /app folder:
    • app.helloworld.d, app.helloworld.js, app.helloworld.js.map
    • main.d, main.js, main.js.map
  • A static server called lite-server will load the index.html in a browser
  • The browser will be refreshed when application files change
  • The application host will be localhost and the port will be 3000

A possible output will look like what’s shown in Figure 3:

Angular3
Figure 3: Possible output for the preceding code

After the above output, in a few seconds, your default browser will be automatically started and you should see the below output (left image—the page is loading, right image—the final result):

Angular4
Figure 4: Viewing the output in a browser

Congrats! You’ve just finished your first Angular2 JS application.

The complete source code is available here.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories