Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Angular

Angular 2 - Getting Started

2022-07-16

Being new to Angular 2, at first I had also thought that, where to start from and where should I go through for the reference and all. After gone through some of the basic tutorials and lectures, got some basic idea about Angular 2, like what it is, what it does and what can we do with it and all. I'm gonna introduce you the basics of Angular 2 and all the setup process in this blog for your basic understanding. As we go through the concepts, trust me you're gonna enjoy learning it as well as implementing it as I did (You need patience though).

Let's get to it

Angular 2 is an open source Javascript framework to build web applications or single page applications in HTML and Javascript. (I'm not gonna introduce any Angular 1 related topics/content in this or any blog post. I will be comparing the Angular 2 with Angular 1 features at some places.)

Angular 2 comes with almost everything you need to build a complicated or single page frontend web or mobile applications, from powerful templates to fast rendering, data management, data binding, HTTP services, form handling, and so much more.

Why angular 2?

  • Advantage of latest versions of Javascript ES2015/ES6.
  • Web Components.
  • Speed improvements in rendering and response compared to Angular1. It's simpler than Angular 1 and its fewer concepts can make it easier to understand and build better.
  • You can update the large data sets with minimal memory overhead. It'll speed up the initial loading through server side rendering.

Features:

  • It's a cross platform framework.
  • It supports all latest browser versions and also supports some old browsers including IE9+ and Android 4.1+.
  • Code structure is simplified than the previous version, that makes this version of angular simpler, faster, easier to understand and also to implement.

Advantages:

  • In Angular everything is a component based approach.
  • If an application is heavy to load, then angular 2 keeps it fully UI responsive to save the response time and the load time.
  • For mobiles it uses server side rendering for faster response.
  • It works well with ECMAScript (or ES - commonly use ECMAScript for client-side scripting on the World Wide Web, and it is increasingly being used for writing server applications and services using Node.js. Other implementations of ECMAScript include JScript and ActionScript) and other languages that compile to Javascript.
  • It uses dependency injection to maintain applications without writing too long code.

What is TypeScript?

TypeScript is a superset of Javascript which is having all the features we used in javascript and also having the advanced features like decorators, types and etc,.

__________________________________
  |   Typescript                   |
  |   + ES7                        |
  |   + Decorators                 |
  |   + Types                      |
  |   ___________________________  |
  |   |   ES6                    | |
  |   |   + Classes              | |
  |   |   + Modules              | |
  |   |   + More ...             | |
  |   |     ____________________ | |
  |   |     |  ES5              || |
  |   |     |                   || |
  |   |     |                   || |
  |   |     |___________________|| |
  |   |__________________________| |
  |________________________________|

TypeScript benefits and uses:

  • Classes
  • Type Checking
  • Editor support (I personally recomend you to use Sublime or VisualStudio)
  • It's a superset of JavaScript

The structure of a basic angular 2 app:

| - app/
  | ----- app.component.ts  |
  | ----- app.module.ts     | these 3 files belongs to the angular 2 application
  | ----- main.ts           |
  | - index.html
  | - package.json          |
  | - tsconfig.json         | these 4 files are the setup for the project
  | - typings.json          |
  | - systemjs.config.js    |

For now index.html is just a basic html as we know so far. It'll be changed as we get know angular in more detail.

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Angular 2 - Getting Started</title>

    <!-- css -->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css">
    <style type="text/css">
      body {
        padding: 50px 0;
      }
    </style>

    <!-- js -->

  </head>
  <body class="container">
    Hello World!
  </body>
  </html>

SetUp process:

Angular applications and Angular itself depend upon features and functionality provided by a variety of third-party packages. These packages are maintained and installed with the Node Package Manager (npm).

Node.js and npm are essential to Angular development.

Installing Node.js

Download nodejs from https://nodejs.org/

To install from a terminal:

$ cd /usr/local
$ tar --strip-components 1 -xJf ~/Downloads/node-v4.4.5-linux-x64.tar.xz

* if not giving write permissions -- just use sudo in front of tar

Update npm:

$ sudo npm install -g npm

Verify that you are running node v4.x.x or higher and npm 3.x.x or higher by running the commands node -v and npm -v in a terminal/console window. Older versions produce errors.

check versions:

$ node -v

$ npm -v
Example:
    //Download
    $ cd ~/Downloads
    $ wget https://nodejs.org/dist/v4.4.5/node-v4.4.5-linux-x64.tar.xz

    //Install
    $ cd /usr/local
    $ tar --strip-components 1 -xJf ~/Downloads/node-v4.4.5-linux-x64.tar.xz

    //Verify
    $ node -v
    $ npm version

Another way of installation:

You can install latest version very easily using below instructions.

$ curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -

// Version 7.x is the latest version of node.

$ sudo apt-get install nodejs

       (or)

$ sudo apt-get install -y nodejs

// Above line will install nodejs.

$ sudo apt-get install build-essential

// This will install essential modules for nodejs to run properly.

Now check whether nodejs installed correctly at the end.

$ nodejs -v

// This will return installed nodejs version.

$ npm -v

// This will return installed npm version.

To install NPM:

$ sudo apt-get install npm

// Then for Node

$ sudo npm cache clean -f
$ sudo npm install -g n
$ sudo n 0.xx.x  // here is the version what you want..

You can remove and install:

$ apt-get remove --purge nodejs npm
$ curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
$ apt-get install nodejs

Updating npm

$ npm install npm@latest -g

initial package.json file

{
    "name": "angular2-getting-started",
    "vesion": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "lite": "lite-server"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "lite-server": "^2.2.2",
      "typescript": "^1.8.10",
      "typings": "^1.3.2"
    }
  }

We need to install typescript and also typings using npm package installer:

npm install --save-dev typescript typings

After installing typescript and typings in our app modules, we have to create two files named tsconfig.json & typings.json to configure.

<-- If you are a ubuntu/linux user, you can use touch to create these files -->

 $ touch tsconfig.json typings.json

We'll be configuring the tsconfig.json file first:

{
    "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": false,
      "lib": [ "es2015", "dom" ],
      "noImplicityAny": false
    }
  }

Now we'll be needing the global typings tools, so we're gonna install typings using npm package installer again.

$ npm install -g typings

Here, what we've to understand is, if you install any dependencies of typings using typings like below explained command, the dependencies will be listed in typings.json file.

$ typings install dt~core-js dt~jasmine dt~node --save --global

  core-js
  `-- (No dependencies)

  jasmine
  `-- (No dependencies)

  node
  `-- (No dependencies)

In typings.json file

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

After installing the typescript and typings, we have to configure the config.json file also

{
    "name": "angular2-getting-started",
    "vesion": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "lite": "lite-server",
      "tsc": "tsc",
      "tsc:w": "tsc -w",
      "typings": "typings",
      "postinstall": "typings install"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "lite-server": "^2.2.2",
      "typescript": "^1.8.10",
      "typings": "^1.3.2"
    }
  }

Now, we have to run the typescript and typings packages simultaneously. How? That's why we are gonna use a special package called "concurrently" which runs lite-server and typescript watch packages at a time. For that we need to install it, by using below command.

$ npm install concurrently --save-dev

After installing the concurrently package of npm, we have to configure the config.json file again to include a comman to run both lite-server and also typescript watch packages simultaneously.

<-- we'll include a start command here -->

  {
    "name": "angular2-getting-started",
    "vesion": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"",
      "lite": "lite-server",
      "tsc": "tsc",
      "tsc:w": "tsc -w",
      "typings": "typings",
      "postinstall": "typings install"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "lite-server": "^2.2.2",
      "typescript": "^1.8.10",
      "typings": "^1.3.2"
    }
  }

After configuring the config.json file, you can give that file a shot to test whether it is working fine or not by typing below comman in shell in the app folder

$ npm start

  > angular2-gettings-started@1.0.0 start /home/<path to the project>/project
  > concurrently "npm run tsc:w" "npm run lite"

  [1]
  [1] > angular2-gettings-started@1.0.0 lite /home/<path to the project>/project
  [1] > lite-server
  [1]
  [0]
  [0] > angular2-gettings-started@1.0.0 tsc:w /home/<path to the project>/project
  [0] > tsc -w
  [0]
  [1] Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
  [1] ** browser-sync config **
  [1] { injectChanges: false,
  [1]   files: [ './**/*.{html,htm,css,js}' ],
  [1]   watchOptions: { ignored: 'node_modules' },
  [1]   server: { baseDir: './', middleware: [ [Function], [Function] ] } }
  [1] [BS] Access URLs:
  [1]  --------------------------------------
  [1]        Local: http://localhost:3000
  [1]     External: http://192.168.0.135:3000
  [1]  --------------------------------------
  [1]           UI: http://localhost:3001
  [1]  UI External: http://192.168.0.135:3001
  [1]  --------------------------------------
  [1] [BS] Serving files from: ./
  [1] [BS] Watching files...
  [1] [BS] File changed: app/app.component.js
  .................
  ................. <here the files watching mode log will be appeared>
  [1] [BS] File changed: app/main.js
  [0] 11:36:29 AM - Compilation complete. Watching for file changes.
  [1] 17.01.30 11:36:34 200 GET /index.html
  [1] 17.01.30 11:36:34 200 GET /styles.css
  .................
  ................. <here the watching mode will wait for the file changes and logs the changes>

Why do we need Angular Dependencies to run our Angular app?

The feature we are using in ES6 are not supported by all the web browsers, that's why we are brining TypeScript and System.js (loader). So System.js will transpile the ES6 code to browser understandable Javascript code.
We are going to use:

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

@Component({ <-- decorator
  selector: 'hello-world',
    template: '<h1>Hello World!</h1>'
})
export class HelloWorldComponent {}
  • Core Js (It patches the features of ES6 to the browser)
  • Zone.js (Create an execution context around our applicaiton - like entire stack of where the app running, erros log - like in which line of the code is causing the error in which file and why)
  • Reflect Metadata (Which allows us to create decorator metadata for our classes)
  • RxJS (It's a reactive, it is going to be a set of libraries that helps us do this. It helps us to create asynchronous data streams using "Observables". - will explain these observables as we go deep into the concepts of Observables where we use to subscribe the promises to retrieve the data. - You can visit it's main page @http://reactivex.io)
  • SystemJS (We'll bring this in, so we can load different modules across different files in our browser.)

Let's install all these dependencies:

There are two ways to install these dependencies.

  • Through shell using npm package installer
  • By keeping the dependencies in package.json file under dependencies section:

1. Through shell using npm package installer

$ npm install core-js reflect-metadata zone.js rxjs@5.0.0-beta.6 systemjs --save

- symbol-observable@1.0.4 node_modules/symbol-observable
angular2-getting-started@1.0.0 /home/<path to the project>/project
+-- core-js@2.4.1
+-- reflect-metadata@0.1.9
+-- rxjs@5.0.0-beta.6
+-- systemjs@0.19.40
`-- zone.js@0.7.6

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.0.17: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN angular2-getting-started@1.0.0 No description

2. Using package.json file

<-- update the config with packages that we want to install -->

  {
    "name": "angular2-getting-started",
    "vesion": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"",
      "lite": "lite-server",
      "tsc": "tsc",
      "tsc:w": "tsc -w",
      "typings": "typings",
      "postinstall": "typings install"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.9",
        "rxjs": "^5.0.0-beta.6",
        "systemjs": "^0.19.40",
        "underscore": "^1.8.3",
        "zone.js": "^0.7.6"
    },
    "devDependencies": {
      "concurrently": "^3.1.0",
        "lite-server": "^2.2.2",
        "typescript": "~2.0.10",
        "jasmine-core": "~2.4.1",
        "@types/node": "^6.0.46",
        "@types/jasmine": "^2.5.36",
      "typings": "^1.3.2"
    }
  }

    ----------------------------------------------------

  $ sudo npm install <-- sometimes using npm install doesn't work, there we have to use root shell by keeping sudo infront of the npm install package command
  [sudo] password for <host_name>: ************** < enter your password here and proceed >

  [email protected] typings install /home/<path to the project>/project
  [email protected] /home/<path to the project>/project
  +-- @types/[email protected]
  +-- @types/[email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  +-- [email protected]
  | `-- [email protected]
  +-- [email protected]
  | `-- [email protected]
  +-- [email protected]
  +-- [email protected]
  | +-- [email protected]
  | +-- [email protected]
  | +-- [email protected]
  | +-- [email protected]
  |  ..................
  |  < related dependencies will be installed >
  |  ..................
  +-- [email protected] 
  `-- [email protected]

Angular Core packages that we need to run the app:

  • @angular/core
  • @angular/common
  • @angular/compiler
  • @angular/platform-browser
  • @angular/platform-browser-dynamic

We can install through shell script:

$ npm install @angular/core @angular/common @angular/compiler @angular/platform-browser @angular/platform-browser-dynamic --save

We can install these packages by configuring the packages in package.json file and install using npm install command:

<-- update the config with packages that we want to install -->
  {
    "name": "angular2-getting-started",
    "vesion": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"",
      "lite": "lite-server",
      "tsc": "tsc",
      "tsc:w": "tsc -w",
      "typings": "typings",
      "postinstall": "typings install"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@angular/common": "~2.4.0",
        "@angular/compiler": "~2.4.0",
        "@angular/core": "~2.4.0",
        "@angular/platform-browser": "~2.4.0",
        "@angular/platform-browser-dynamic": "~2.4.0",
        "angular-in-memory-web-api": "~0.2.4",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.9",
        "rxjs": "^5.0.0-beta.6",
        "systemjs": "^0.19.40",
        "underscore": "^1.8.3",
        "zone.js": "^0.7.6"
    },
    "devDependencies": {
      "concurrently": "^3.1.0",
        "lite-server": "^2.2.2",
        "typescript": "~2.0.10",
        "jasmine-core": "~2.4.1",
        "@types/node": "^6.0.46",
        "@types/jasmine": "^2.5.36",
      "typings": "^1.3.2"
    }
  }

  ----------------------------------------------------

  $ sudo npm install <-- sometimes using npm install doesn't work, there we have to use root shell by keeping sudo infront of the npm install package command
  [sudo] password for <host_name>: ************** < enter your password here and proceed >

  [email protected] typings install /home/<path to the project>/project
  [email protected] /home/<path to the project>/project
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  |  ..................
  |  < related dependencies will be installed >
  |  ..................
  +-- [email protected] 
  `-- [email protected]

Angular Extra Packages:

  • @angular/http
  • @angular/forms
  • @angular/router
  • @angular/upgrade (not really required - if you're looking for upgrading your applications, this might be useful)

Installing the mentioned packages using npm:

$ npm install @angular/http @angular/forms @angular/router @angular/upgrade --save

We can install these packages by configuring in the package.json file and using npm install command:

<-- update the config with packages that we want to install -->
  {
    "name": "angular2-getting-started",
    "vesion": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"",
      "lite": "lite-server",
      "tsc": "tsc",
      "tsc:w": "tsc -w",
      "typings": "typings",
      "postinstall": "typings install"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@angular/common": "~2.4.0",
        "@angular/compiler": "~2.4.0",
        "@angular/core": "~2.4.0",
        "@angular/forms": "~2.4.0",
        "@angular/http": "~2.4.0",
        "@angular/platform-browser": "~2.4.0",
        "@angular/platform-browser-dynamic": "~2.4.0",
        "@angular/router": "~3.4.0",
        "angular-in-memory-web-api": "~0.2.4",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.9",
        "rxjs": "^5.0.0-beta.6",
        "systemjs": "^0.19.40",
        "underscore": "^1.8.3",
        "zone.js": "^0.7.6"
    },
    "devDependencies": {
      "concurrently": "^3.1.0",
        "lite-server": "^2.2.2",
        "typescript": "~2.0.10",
        "jasmine-core": "~2.4.1",
        "@types/node": "^6.0.46",
        "@types/jasmine": "^2.5.36",
      "typings": "^1.3.2"
    }
  }

  ----------------------------------------------------

  $ sudo npm install <-- sometimes using npm install doesn't work, there we have to use root shell by keeping sudo infront of the npm install package command
  [sudo] password for <host_name>: ************** < enter your password here and proceed >

  [email protected] typings install /home/<path to the project>/project
  [email protected] /home/<path to the project>/project
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  +-- @angular/[email protected]
  |  ..................
  |  < related dependencies will be installed >
  |  ..................
  +-- [email protected]
  `-- [email protected]

  npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
  npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
  npm WARN [email protected] No description

SystemJS Loader

<-- for example -->

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

This import part is of ES6 (part of ES6 specifications). The broswers doesn't understand/support this kind of imports for now. Browsers doesn't know where to look for it. How to configure then?

There the SystemJS comes into the picture. This is important for this step (Which tells the browser where to look for the imported packages and all).

<-- create a file called systemjs.config.js -->

  /**
   * System configuration for Angular samples
   * Adjust as necessary for your application needs.
   */
  (function (global) {
    System.config({
      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/bundles/in-memory-web-api.umd.js'
      },
      // 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);

Updating the index.html with libraries and modules we've configured until now:

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Angular 2 - Getting Started</title>

    <!-- css -->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">

    <!-- js -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- 1. Load libraries -->
      <!-- IE required polyfill -->
    <!-- load the dependencies -->
    <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>

      <!-- 2. Load our 'modules' -->
    <!-- load our angular app with systemjs -->
      <script src="node_modules/systemjs/dist/system.src.js"></script>
      <script src="systemjs.config.js"></script>
      <script>
        System.import('app').catch(function(err){ console.error(err); });
      </script>

  </head>
  <!-- 3. Display the application -->
  <body class="container">
    Hello World!
  </body>
  </html>

Here, we can also add external styling sheet. Create a file with name styles.css as we included in the above html. For example:

<!-- styles.css -->

  h1 {
    color: #369;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 250%;
  }
  body {
    margin: 2em;
  }

   /*
    * See https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css
    * for the full set of master styles used by the documentation samples
    */

Till now, we've done

  • Setup of our project
  • Installed TypeScript, angular dependencies, angular packages
  • Loaded all the installed packages with system.js (SystemJS)

Now, we are gonna build our Angular 2 app with these changes and enhancements we've done until now.

We are gonna need five files to build our angular app at first.

| - app/
  | ----- app.component.ts
  | ----- app.module.ts
  | ----- main.ts
  | - index.html            |
  | - package.json          |
  | - tsconfig.json         | these 5 files are the basic setup files
  | - typings.json          | for the every basic angular app project
  | - systemjs.config.js    |

  /*
    Go and copy these files anywhere in a new directory to use as setup for the app.
    From the command line, go into that folder and run: npm install
    (the packages listed in package.json file will be installed).
    You should now see node_modules and typings folders.
    This current directory will be ready to use as scratch to build an angular app now.
  */

Let's get started with the Angular 2 concepts now:

You've the structure of our basic Angular application.

Under the app folder, create a new file called app.component.ts and start building your first angular app.

<-- in app.component.ts -->

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

  @Component({
      selector: 'my-app',
      template: '<h1>Hello World through the Angular App!</h1>'
    })

    export class AppComponent {}

We need to create an angular module and then we need to bootstrap it, So that, we can use it in our app.

We need to create app.module.ts to encapsulate all our components in the app into one central location called module.

<-- app.module.ts -->

  import { NgModule }     from '@angular/core';
  import { BrowserModule }  from '@angular/platform-browser';
  import { AppComponent }   from './app.component';

  @NgModule ({
    imports: [ BrowserModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
  })

  export class AppModule {}

We've created NgModule file, now let's bootstrap it. Create a file called main.ts.

<-- main.ts -->

  import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  import { AppModule }        from './app.module'

  platformBrowserDynamic().bootstrapModule(AppModule);

Now, we got to enhance our index.html. Actually, the selector of our app component will be looking for my-app element. Currently, the html doesn't consist any, so, will get an error. Let's get started enhancing the html then. We just relace the Hello World! with <my-app></my-app> selector.

<-- in index.html -->

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Angular 2 - Getting Started</title>

    <!-- css -->
    <link rel="stylesheet" type="text/css"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">

    <!-- js -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- 1. Load libraries -->
    <!-- IE required polyfill -->
    <!-- load the dependencies -->
    <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>

    <!-- 2. Load our 'modules' -->
    <!-- load our angular app with systemjs -->
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>

  </head>
  <!-- 3. Display the application -->
  <body class="container">
    <my-app>Loading ....</my-app> <-- here we just relaced the text with element selectors -->
  </body>
  </html>

Now, go back to the browser and you'll see the app with "Hello World through the Angular App!" text in h1 formatted text.

That's the end of Angular 2 - Getting started. And will continue with the next part (How to use these components to build our own angular 2 app?) in another blog post.

For your basic knowledge, listing you the anatomy of components and all the related basic typescript classes to build our angular app. See the given examples below:

Component Anatomy - Inline Template

<!-- hello-world.component.ts -->
                             import { component } from '@angular/core';

 @component decorator -->    @Component({
    CSS Selector  -->            selector: 'hello-world',
    Template  -->                template: '<h1>Hello World!</h1>'
                             })
    Class declaration -->    export class HelloWorldComponent {}

Component Anatomy - Template File

<!-- hello-world.component.ts -->
                             import { component } from '@angular/core';

 @component decorator -->    @Component({
    CSS Selector  -->            selector: 'hello-world',
    Template  -->                templateUrl: './hello-world.component.html'
                             })
    Class declaration -->    export class HelloWorldComponent {}

 <!-- hello-world.component.html -->

 <h1>Hello World!</h1>

Module Anatomy

<!-- app.module.ts -->
                             import { NgModule } from '@angular/core';
                             import { HelloWorldComponent } from './hello-world.component';

 @NgModule decorator  -->    @NgModule({
 Component to include -->        declarations: [ HelloWorldComponent ],
    Root Component(s) -->        bootstrap: [ HelloWorldComponent ],
                               })
    Class declaration -->    export class AppModule {}

Module Bootstrapping

<!-- main.ts -->
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

paltformBrowserDynamic().bootstrapModule(AppModule);

You can change the selector name to any name that describes your app or whatever you want to keep, instead of <my-app></my-app> in index.html

<!-- index.html -->

  <body>

    <!-- from the scratch at first we'll be having <b><my-app></my-app></b> as selector to our "root" component -->

    <hello-world>Loading...</hello-world>

  </body>