Angular 2 Getting started with Angular 2 Getting started with Angular 2 without angular-cli.


Example

Angular 2.0.0-rc.4

In this example we'll create a "Hello World!" app with only one root component (AppComponent) for the sake of simplicity.

Prerequisites:

  • Node.js v5 or later
  • npm v3 or later

Note: You can check versions by running node -v and npm -v in the console/terminal.

Step 1

Create and enter a new folder for your project. Let's call it angular2-example.

mkdir angular2-example
cd angular2-example

Step 2

Before we start writing our app code, we'll add the 4 files provided below: package.json, tsconfig.json, typings.json, and systemjs.config.js.

Disclaimer: The same files can be found in the Official 5 Minute Quickstart.

package.json - Allows us to download all dependencies with npm and provides simple script execution to make life easier for simple projects. (You should consider using something like Gulp in the future to automate tasks).

{
  "name": "angular2-example",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.14",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
}

tsconfig.json - Configures the TypeScript transpiler.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

typings.json - Makes TypeScript recognize libraries we're using.

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}

systemjs.config.js - Configures SystemJS (you can also use webpack).

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application's needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

Step 3

Let's install the dependencies by typing

npm install

in the console/terminal.

Step 4

Create index.html inside of the angular2-example folder.

<html>
  <head>
    <title>Angular2 example</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/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></my-app>
  </body>
</html>

Your application will be rendered between the my-app tags.

However, Angular still doesn't know what to render. To tell it that, we'll define AppComponent.

Step 5

Create a subfolder called app where we can define the components and services that make up our app. (In this case, it'll just contain the AppComponent code and main.ts.)

mkdir app

Step 6

Create the file app/app.component.ts

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

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <ul>
        <li *ngFor="let message of messages">
            {{message}}
        </li>
    </ul>
  `
})
export class AppComponent { 
    title = "Angular2 example";
    messages = [
        "Hello World!",
        "Another string",
        "Another one"
    ];
}

What's happening? First, we're importing the @Component decorator which we use to give Angular the HTML tag and template for this component. Then, we're creating the class AppComponent with title and messages variables that we can use in the template.

Now let's look at that template:

<h1>{{title}}</h1>
<ul>
    <li *ngFor="let message of messages">
        {{message}}
    </li>
</ul>

We're displaying the title variable in an h1 tag and then making a list showing each element of the messages array by using the *ngFor directive. For each element in the array, *ngFor creates a message variable that we use within the li element. The result will be:

<h1>Angular 2 example</h1>
<ul>
    <li>Hello World!</li>
    <li>Another string</li>
    <li>Another one</li>
</ul>

Step 7

Now we create a main.ts file, which will be the first file that Angular looks at.

Create the file app/main.ts.

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

bootstrap(AppComponent);

We're importing the bootstrap function and AppComponent class, then using bootstrap to tell Angular which component to use as the root.

Step 8

It's time to fire up your first app. Type

npm start

in your console/terminal. This will run a prepared script from package.json that starts lite-server, opens your app in a browser window, and runs the TypeScript transpiler in watch mode (so .ts files will be transpiled and the browser will refresh when you save changes).

What now?

Check out the official Angular 2 guide and the other topics on StackOverflow's documentation.

You can also edit AppComponent to use external templates, styles or add/edit component variables. You should see your changes immediately after saving files.