Angular 2


Improvements requested by Yurgi, Community, Community:

  • This topic would benefit from additional syntax notation, explanation of parameters, or remarks. ×3 - jul 21 at 10:17
    Comments:
    • It would be beneficial to outline how to install angular2 without using angular-cli. What if a developer likes to develop from scratch and avoid using scaffolding tools? - Yurgi
    • Replace the default remarks section with a descriptive overview of angular2. - Community
    • Add a Version section, describing the major releases of angular2 along with links to release notes. - Community

This draft deletes the entire topic.

inline side-by-side expand all collapse all

Examples

  • 4

    This example is a quick setup of angular2 and how to generate a quick example project.

    Prerequisite:

    Open a terminal and run the commands one by one:

    npm install -g typings
    npm install -g angular-cli
    

    You now have angular-cli installed and ready. Navigate with the terminal to a folder where you want to set up the new project.

    Run the commands:

    ng new PROJECT_NAME
    cd PROJECT_NAME
    ng serve
    

    That is it, you now have a simple example project made with angular 2. You can now navigate to the link displayed in terminal and see what it is running.

    For more info also visit: angular-cli github page

    Adding Routes

    ** Note: the angular-cli team are actively working on the route functionality so this may be subject to change **

    ng g route ROUTE_NAME 
    

    or the concise syntax

    ng g r ROUTE_NAME
    
  • 3

    Angular 2.0.0-rc.4

    In this example we'll create a little bit more complicated "Hello World!" app which will include only one root component (AppComponent) for the sake of simplicity.

    Prerequisites:

    • At least node v5.x.x
    • At least npm v3.x.x

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

    Step 1

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

    mkdir angular2-example
    cd angular2-example
    

    Step 2

    To make it easier we'll add 4 files provided below: package.json, tsconfig.json, typings.json and systemjs.config.js

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

    package.json - It allows us to download all dependencies thanks to npm and brings simple script to make life easier at the beginning. (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 - Configuration of TypeScript transpiler.

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

    typings.json - It 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 - Configuration of SystemJS (you can also use webpack).

    /**
     * System configuration for Angular 2 samples
     * Adjust as necessary for your application 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 all dependencies by typing

    npm install
    

    in the console/terminal.

    Step 4

    Create index.html file inside of 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 is then rendered inside:

    <my-app></my-app>
    

    Angular2 will know what to do with it after creating main.ts and app.component.ts files.

    Step 5

    Create app subfolder in which we'll hold .ts, .js, .html (external templates) and .css files.

    mkdir app
    

    Step 6

    After installing all dependencies and creating index.html file we can start writing some code that matters to bring your first Angular2 app to life!

    Create app/app.component.ts file.

    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",
            "Another one",
            "Another one",
            "...",
            "Another one"
        ];
    }
    

    What's happening? First we're importing @Component decorator which will tell Angular2 which tag and template this component uses. We'll come back shortly to template. Next we're creating AppComponent class with variables which can be used in your template. These are title (string) and messages (array of strings).

    Now let's look at the template:

    /* ... */
    @Component({
          selector: 'my-app',
          template: `
            <h1>{{title}}</h1>
            <ul>
                <li *ngFor="let message of messages">
                    {{message}}
                </li>
            </ul>
          `
        }) /* ... */
    

    First please note that this is a ES6's template string which allows us to break lines and make it more readable in that case.

    We're putting title variable into h1 tag and then we're making a list which shows every element of the messages array by using *ngFor functionality. It literally means "create message variable for each element of messages array" and we can use it in the tag's scope. It works like for each loop in this case. The final effect will be h1 tag with "Angular2 example" message and list with 7 bullets (7 li tags).

    Step 7

    Now we've to create main.ts file which is the first file looked up by Angular2.

    Create app/main.ts file.

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

    We're importing bootstrap function, AppComponent class and using bootstrap function to tell which component is a root one.

    Step 8

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

    npm start
    

    in your console/terminal. It'll run a prepared script from package.json file which runs lite-server and typescript transpiler in watch mode (browser we'll be refreshed when changes appear and .ts files will be transpiled).

    A few moments later your browser should open your app's page and show the results.

    What now?

    I'd recommend checking out Angular2 documentation and tutorials and also 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.

  • 2

    The easiest way to get started with Angular 2 is by using the angular-cli build by the angular team.

    First, you need to install the tool: npm install -g angular-cli.

    Now you can start using it.

    Creating a new project: ng new projectname.

    Launching a development server: ng serve.

    Creating a new component ng generate component home.

    You can also use the short syntax: ng g c home.

    With angular CLI it is very easy to create components, routes, services, directives and tests.

    Angular-CLI saves a lot of time building and scaffolding application structure, because it puts all the needed files in the right places, creates tests automatically and uses the best practices found by many Angular 2 developers.

I am downvoting this example because it is...

Remarks

This section provides an overview of how to install and configure Angular2 for use in various environments and IDE's using tools like the community developed angular-cli.

Versions

Versions

Still have a Install Angular2 question? Ask Question

Install angular2 with angular-cli

4

This example is a quick setup of angular2 and how to generate a quick example project.

Prerequisite:

Open a terminal and run the commands one by one:

npm install -g typings
npm install -g angular-cli

You now have angular-cli installed and ready. Navigate with the terminal to a folder where you want to set up the new project.

Run the commands:

ng new PROJECT_NAME
cd PROJECT_NAME
ng serve

That is it, you now have a simple example project made with angular 2. You can now navigate to the link displayed in terminal and see what it is running.

For more info also visit: angular-cli github page

Adding Routes

** Note: the angular-cli team are actively working on the route functionality so this may be subject to change **

ng g route ROUTE_NAME 

or the concise syntax

ng g r ROUTE_NAME

Getting started with Angular2 without angular-cli.

3

Angular 2.0.0-rc.4

In this example we'll create a little bit more complicated "Hello World!" app which will include only one root component (AppComponent) for the sake of simplicity.

Prerequisites:

  • At least node v5.x.x
  • At least npm v3.x.x

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

Step 1

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

mkdir angular2-example
cd angular2-example

Step 2

To make it easier we'll add 4 files provided below: package.json, tsconfig.json, typings.json and systemjs.config.js

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

package.json - It allows us to download all dependencies thanks to npm and brings simple script to make life easier at the beginning. (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 - Configuration of TypeScript transpiler.

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

typings.json - It 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 - Configuration of SystemJS (you can also use webpack).

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application 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 all dependencies by typing

npm install

in the console/terminal.

Step 4

Create index.html file inside of 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 is then rendered inside:

<my-app></my-app>

Angular2 will know what to do with it after creating main.ts and app.component.ts files.

Step 5

Create app subfolder in which we'll hold .ts, .js, .html (external templates) and .css files.

mkdir app

Step 6

After installing all dependencies and creating index.html file we can start writing some code that matters to bring your first Angular2 app to life!

Create app/app.component.ts file.

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",
        "Another one",
        "Another one",
        "...",
        "Another one"
    ];
}

What's happening? First we're importing @Component decorator which will tell Angular2 which tag and template this component uses. We'll come back shortly to template. Next we're creating AppComponent class with variables which can be used in your template. These are title (string) and messages (array of strings).

Now let's look at the template:

/* ... */
@Component({
      selector: 'my-app',
      template: `
        <h1>{{title}}</h1>
        <ul>
            <li *ngFor="let message of messages">
                {{message}}
            </li>
        </ul>
      `
    }) /* ... */

First please note that this is a ES6's template string which allows us to break lines and make it more readable in that case.

We're putting title variable into h1 tag and then we're making a list which shows every element of the messages array by using *ngFor functionality. It literally means "create message variable for each element of messages array" and we can use it in the tag's scope. It works like for each loop in this case. The final effect will be h1 tag with "Angular2 example" message and list with 7 bullets (7 li tags).

Step 7

Now we've to create main.ts file which is the first file looked up by Angular2.

Create app/main.ts file.

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

bootstrap(AppComponent);

We're importing bootstrap function, AppComponent class and using bootstrap function to tell which component is a root one.

Step 8

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

npm start

in your console/terminal. It'll run a prepared script from package.json file which runs lite-server and typescript transpiler in watch mode (browser we'll be refreshed when changes appear and .ts files will be transpiled).

A few moments later your browser should open your app's page and show the results.

What now?

I'd recommend checking out Angular2 documentation and tutorials and also 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.

Installation or Setup

2

The easiest way to get started with Angular 2 is by using the angular-cli build by the angular team.

First, you need to install the tool: npm install -g angular-cli.

Now you can start using it.

Creating a new project: ng new projectname.

Launching a development server: ng serve.

Creating a new component ng generate component home.

You can also use the short syntax: ng g c home.

With angular CLI it is very easy to create components, routes, services, directives and tests.

Angular-CLI saves a lot of time building and scaffolding application structure, because it puts all the needed files in the right places, creates tests automatically and uses the best practices found by many Angular 2 developers.

Topic Outline