Angular2 Hello World Example | JavaInUse




Set up Angular 2 local development environment using npm(Node Package Manager)

Overview

This chapter covers minimum required configuration for creating hello world based application in angular using Typescript. We will create an Angular 2 Application with NPM. First, make sure you have Node.js and npm installed.

You can read instructions how to install node and npm HERE, if not already on your machine.

Lets Begin

Create a new project folder

First create a folder with the following command in Terminal. The following command will create a folder and set your base directory to folder we just created. Folder Structure Image goes here

mkdir  Angular2-helloworld-example && cd  Angular2-helloworld-example

Creating tsconfig.json

We will create the tsconfig.json as follows-
{
  "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"
  ]
}

What is the tsconfig.json file?

Basically tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.
It also provides information about compiling process typescript into javascript. In which version should be compiled ts, should js files include source maps, and such information usually described in this file.

Adding typings.json

Next we have to add a typings.json file to the project folder and paste the following code.
{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b"
  }
}

What is the typings.json file?

Typings is the simple way to manage and install TypeScript definitions. It uses typings.json, which can resolve to the Typings Registry, GitHub, NPM, Bower, HTTP and local files. Packages can use type definitions from various sources and different versions, knowing they will never conflict for users.
This typings.json file allows TypeScript compiler to recognise external type definitions of the existing JavaScript libraries.

Adding node dependencies and devDependencies in new file called package.json

Next we have to add a package.json file to the project folder and copy/paste the following code.
{
  "name": " Angular2-helloworld-example",
  "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"
  }
}

What is the package.json file?

All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies.
It includes information about packages and libraries which are used by your project, also can include npm scripts which helps of running tasks of application like running tests, building js and so on...
“dependencies” contains all dependencies used in our application to implement the functionality we want to have and we could add other entries for example for bootstrap or jquery.
“devDependencies” section is listening the dependencies required at development time only.

Install packages

Enter the following npm command in command prompt window to install all packages described above to our project.
npm install

Creating 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-example/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 = 'First angular App';
     }
}

What’s a component?

In Angular 2, components are a fundamental concept. It is the way we define views and control the logic on the page. We passed in a configuration object to the component decorator. This object has two properties : selector and template. The selector is the HTML element that angular will looking for. Every times it founds one, angular will instantiate a new instance of our AppComponent class, and place our template.

As you may also notice we export our class at the end. All classes in TypeScript have a constructor, whether you specify one or not. If you do not define the constructor, the compiler will automatically add one. The constructor is called before any other component lifecyle hook. If the component has any dependencies, the constructor is the best place to inject those dependencies. The export statement tells TypeScript that this is a module whose AppComponent class is public and accessible to other modules of the application.

To identify to angular that there is a component, we use the @Component decorator and to be able to use it

Add the appComponent template.

Adding app.html inside the app folder and copy/paste with the following snippet:
<h1>Wel-come to {{target}}!!!!</h1>

We put our declared variable target inside double curly brackets like we always do.

Bootstrapping our app

Create a new file called main.ts also inside app folder and copy/paste with the following snippet:
//  Angular2-Helloworld-Example/app/main.ts

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

bootstrap(AppComponent);  

What does Bootstrapping our app means?

The bootstrap method is a promise object and the first parameter we define is the main class of our app - the component; that’s why we had to import {AppComponent} from './app.component’.

We were able to import this class because we used the ’export’ keyword which makes the class public across the project. As per the example above, inside the brackets {} is the name of our class and from ‘’ is where the file of that class is located. Because we have all the files in the main root we don’t need to include any folder or sub folder to locate the component (ex: ‘. /app/app.component’). At the moment we do not need to worry about the folder structure because it is a basic example; however, the second parameter of the bootstrap method is where we can have an array that contains a list of what we want to make available for injection.

The import statement tells the system it can get an AppComponent from a module namedapp.component located in a neighboring file. The module name (AKA module id) is often the same as the filename without its extension.

Add the main web page index.html

Create a new file called index.html file in our project root folder and copy/paste with the following snippet:
<!DOCTYPE html>
<html>  
  <head>
    <title>My First Angular 2 App</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>
Angular 2 is bundled in modules, and these modules can be loaded dynamically. To load our module we are relying on a tool SystemJS which is a small module loader. We added it statically into our HTML and it tells where the modules are located in our server. It then automatically figures out the dependencies between modules and downloads the ones used from our application.

System.import('app/main');

‘app/main’ — Indicates where is located our main.js and if you did not change your tsconfig.json, you should not have any problems loading the JS file.
npm start image

Welcome page goes here

Download Source Code

Download it - Angular2 Hello World Example
 

See Also

Removing the # from the AngularJS URL Use Google reCaptcha with AngularJS Use AngularJS NgCloak directives Example PrimeNG-UI Components for AngularJS 2 Basic Example