Angular 2


Improvements requested:

  • This topic would benefit from additional syntax notation, explanation of parameters, or remarks. –  Community Jul 21 at 10:17
    Add a Version section, describing the major releases of angular2 along with links to release notes.
    1. A version section has been added
  • This topic would benefit from additional syntax notation, explanation of parameters, or remarks. –  Community Jul 21 at 10:17
    Replace the default remarks section with a descriptive overview of angular2.
    1. 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?

This draft deletes the entire topic.

expand all collapse all

Examples

  • 7

    We will create a simple "Hello World!" app with Angular2 2.4.1 (@NgModule change) with a node.js (expressjs) backend.

    Prerequisites

    Then run npm install -g typescript to install typescript globally

    Roadmap

    Step 1

    Create a new folder (and the root dir of our back-end) for our app. Let's call it Angular2-express.

    command line:

    mkdir Angular2-express
    cd Angular2-express
    

    Step2

    Create the package.json (for dependencies) and app.js (for bootstrapping) for our node.js app.

    package.json:

    {
      "name": "Angular2-express",
      "version": "1.0.0",
      "description": "",
      "scripts": {
        "start": "node app.js"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "body-parser": "^1.13.3",
        "express": "^4.13.3"
      }
    }
    

    app.js:

    var express = require('express');
    var app = express();
    var server = require('http').Server(app);
    var bodyParser = require('body-parser');
    
    server.listen(process.env.PORT || 9999, function(){
        console.log("Server connected. Listening on port: 9999");
    });
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}) );
    
    app.use( express.static(__dirname + '/front' ) );
    

    Then run an npm install to install the dependencies.

    Now our back-end structure is complete. Let's move on to the front-end.

    Step3

    Our front-end should be in a folder named front inside our Angular2-express folder.

    command line:

    mkdir front
    cd front
    

    Just like we did with our back-end our front-end needs the dependency files too. Let's go ahead and create the following files: package.json, systemjs.config.js, tsconfig.json

    package.json:

    {
      "name": "Angular2-express",
      "version": "1.0.0",
      "scripts": {
        "tsc": "tsc",
        "tsc:w": "tsc -w"
      },
      "licenses": [
        {
          "type": "MIT",
          "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
        }
      ],
      "dependencies": {
        "@angular/common": "~2.4.1",
        "@angular/compiler": "~2.4.1",
        "@angular/compiler-cli": "^2.4.1",
        "@angular/core": "~2.4.1",
        "@angular/forms": "~2.4.1",
        "@angular/http": "~2.4.1",
        "@angular/platform-browser": "~2.4.1",
        "@angular/platform-browser-dynamic": "~2.4.1",
        "@angular/platform-server": "^2.4.1",
        "@angular/router": "~3.4.0",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.8",
        "rxjs": "^5.0.2",
        "systemjs": "0.19.40",
        "zone.js": "^0.7.4"
      },
      "devDependencies": {
        "@types/core-js": "^0.9.34",
        "@types/node": "^6.0.45",
        "typescript": "2.0.2"
      }
    }
    

    systemjs.config.js:

    /**
     * System configuration for Angular samples
     * Adjust as necessary for your application needs.
     */
    (function (global) {
      System.config({
        defaultJSExtensions:true,
        paths: {
          // paths serve as alias
          'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
          // our app is within the app folder
          app: 'app',
          // angular bundles
          '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
          '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
          '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
          '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
          '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
          '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
          '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
          '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
          // other libraries
          'rxjs':                      'npm:rxjs',
          'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
          app: {
            main: './main.js',
            defaultExtension: 'js'
          },
          rxjs: {
            defaultExtension: 'js'
          }
        }
      });
    })(this);
    

    tsconfig.json:

    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      },
      "compileOnSave": true,
      "exclude": [
        "node_modules/*"
      ]
    }
    

    Then run an npm install to install the dependencies.

    Now that our dependency files are complete. Let's move on to our index.html:

    index.html:

    <html>
      <head>
        <base href="/">
        <title>Angular2-express</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>Loading...</my-app>
      </body>
    </html>
    

    Now we're ready to create our first component. Create a folder named app inside our front folder.

    command line:

    mkdir app
    cd app
    

    Let's make the following files named main.ts, app.module.ts, app.component.ts

    main.ts:

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    import { AppModule } from './app.module';
    
    const platform = platformBrowserDynamic();
    platform.bootstrapModule(AppModule);
    

    app.module.ts:

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppComponent }   from './app.component';
    
    @NgModule({
      imports:      [ 
        BrowserModule    
      ],
      declarations: [ 
        AppComponent
      ],
      providers:[ ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule {}
    

    app.component.ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: 'Hello World!',
      providers: []
    })
    export class AppComponent { 
      constructor(){}
    }
    

    After this, compile the typescript files to javascript files. Go 2 levels up from the current dir (inside Angular2-express folder) and run the command below.

    command line:

    cd ..
    cd ..
    tsc -p front
    

    Our folder structure should look like:

    Angular2-express
    ├── app.js
    ├── node_modules
    ├── package.json
    ├── front
    │   ├── package.json
    │   ├── node_modules
    │   ├── systemjs.config.js
    │   ├── tsconfig.json
    │   ├── app
    │   │   ├── app.component.ts
    │   │   ├── app.component.js.map
    │   │   ├── app.component.js
    │   │   ├── app.module.ts
    │   │   ├── app.module.js.map
    │   │   ├── app.module.js
    │   │   ├── main.ts
    │   │   ├── main.js.map
    │   │   ├── main.js
    

    Finally, inside Angular2-express folder, run node app.js command in the command line. Open your favorite browser and check localhost:9999 to see your app.

  • 39

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

    Prerequisites:

    Open a terminal and run the commands one by one:

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

    The first command installs the typings library globally (and adds the typings executable to PATH). The second installs angular-cli globally, adding the executable ng to PATH.

    To setup a new project

    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.

    To add to an existing project

    Navigate to the root of your current project.

    Run the command:

    ng init
    

    This will add the necessary scaffolding to your project. The files will be created in the current directory so be sure to run this in an empty directory.

    Running The Project Locally

    In order to see and interact with your application while it's running in the browser you must start a local development server hosting the files for your project.

    ng serve
    

    If the server started successfully it should display an address at which the server is running. Usually is this:

    http://localhost:4200
    

    Out of the box this local development server is hooked up with Hot Module Reloading, so any changes to the html, typescript, or css, will trigger the browser to be automatically reloaded (but can be disabled if desired).

    Generating Components, Directives, Pipes and Services

    The ng generate <scaffold-type> <name> (or simply ng g <scaffold-type> <name>) command allows you to automatically generate Angular components:

    # The command below will generate a component in the folder you are currently at
    ng generate component my-generated-component
    # Using the alias (same outcome as above)
    ng g component my-generated-component
    

    There are several possible types of scaffolds angular-cli can generate:

    Scaffold TypeUsage
    Moduleng g module my-new-module
    Componentng g component my-new-component
    Directiveng g directive my-new-directive
    Pipeng g pipe my-new-pipe
    Serviceng g service my-new-service
    Classng g class my-new-class
    Interfaceng g interface my-new-interface
    Enumng g enum my-new-enum

    You can also replace the type name by its first letter. For example:

    ng g m my-new-module to generate a new module or ng g c my-new-component to create a component.

    Building/Bundling

    When you are all finished building your Angular 2 web app and you would like to install it on a web server like Apache Tomcat, all you need to do is run the build command either with or without the production flag set. Production will minifiy the code and optimize for a production setting.

    ng build
    

    or

    ng build --prod
    

    Then look in the projects root directory for a /dist folder, which contains the build.

    If you'd like the benefits of a smaller production bundle, you can also use Ahead-of-Time template compilation, which removes the template compiler from the final build:

    ng build --prod --aot
    

    Unit Testing

    Angular 2 provides in-built unit testing, and every item created by angular-cli generates a basic unit test, that can be expended. The unit tests are written using jasmine, and executed through Karma. In order to start testing execute the following command:

    ng test
    

    This command will execute all the tests in the project, and will re-execute them every time a source file changes, whether it is a test or code from the application.

    For more info also visit: angular-cli github page

  • 27

    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.

Please consider making a request to improve this example.

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.

The previous version of Angular is AngularJS or also named Angular 1. See here the documentation.

Versions

VersionRelease Date
2.4.12016-12-21
2.3.02016-12-08
2.2.02016-11-14
2.1.02016-10-13
2.0.22016-10-05
2.0.12016-09-23
2.0.02016-09-14
2.0.0-rc.72016-09-13
2.0.0-rc.62016-08-31
2.0.0-rc.52016-08-09
2.0.0-rc.42016-06-30
2.0.0-rc.32016-06-21
2.0.0-rc.22016-06-15
2.0.0-rc.12016-05-03
2.0.0-rc.02016-05-02
Still have a question about Getting started with Angular 2? Ask Question

Topic Outline