Angular 2 Hello World

Prerequisite:
  1. Node   2) npm (Node Package Manager)
Install node JS using installer. Download it from nodejs.org
If you already install, then make sure that version is 4 or higher.
Npm will install along with nodejs, for this tutorial version should be 3 or higher. To get npm most recent version run

sudo npm install npm -g
$ npm --version
3.10.9
$ node --version
V6.8.1
Now create a new folder and open it using Terminal.
mkdir angular-helloworld
cd angular-helloworld/

Now we have to create four configuration files now
package.json: This file should be in root of project. It contains metadata about project like version, dependencies, configuration and license information. Which provide information to npm and to end user as well like project description.
tsconfig.json:Provide required information for TypeScript compiler about root files and compiler options for generating JavaScript files, should be in root directory of project.
Typings.json: Provide more information to TypeScript compiler for extended JavaScript syntax and features, which are not recognized by TypeScript compiler natively.
systemjs.config.js:Configuration for SystemJS like where can module be found that should be load by module loader, and all necessary packages that need to be registered. Other packages that are needed later by later documentation example also configure here.

Now install a good code editor, you can use any text editor which is convenient to you. There are may good code and text editor like WebStrom, Visual Studio Code, Notepad++, Brackets and Sublime Text. We will use Visual Studio Code in this tutorial. Its free and open source and available to Windows, MAC and Linux. Download VS Code from code.visualstudio.com.
Install and open VS Code and open explorer from right top corner and then click open folder. Now hover mouse on directory name in VS Code explorer and click on New File . Name file ‘package.json’ and following code.
{
  "name": "angular-helloworld",
  "version": "0.0.1",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/compiler": "~2.1.1",
    "@angular/common": "~2.1.1",
    "@angular/forms": "~2.1.1",
    "@angular/http": "~2.1.1",
    "@angular/router": "~3.1.1",
    "@angular/upgrade": "~2.1.1",
    "@angular/platform-browser": "~2.1.1",
    "@angular/platform-browser-dynamic": "~2.1.1",
    "@angular/core": "~2.1.1",
    "angular-in-memory-web-api": "~0.1.13",
    "core-js": "^2.4.1",
    "systemjs": "0.19.39",
    "zone.js": "^0.6.25",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.12"
  },
  "devDependencies": {
    "@types/node": "^6.0.45",
    "@types/core-js": "^0.9.34",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.3",
    "concurrently": "^3.0.0"
  }
}
Similarly add tsconfig.json,
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}
And systemjs.config.js
(function (global) {
  System.config({
    paths: {
      // alias paths
      'npm:': 'node_modules/'
    },
    // Maps path for System loader
    map: {
       app: 'app',//mapping our application
      // mapping 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',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      // other libraries mapping
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    //Provide default informaion for file and extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
 Now in VS Code goto View > Intergrated Terminal. Terminal window will appear in bottom. Now to install packages in package.json run below command.

npm install
You may see some warning messages at the end of installation like npm WARN, until your error message starting with npm ERR.
Till now your directory structure will be

drwxr-xr-x  268 node_modules         (directory)            
-rw-r--r--    1 package.json                   
-rw-r--r--    1 systemjs.config.js             
-rw-r--r--    1 tsconfig.json  

One directory and 3 files.
Now we start code
Angular Module is a part of application. Angular itself is divided into parts of functionality. One module may have many sub model. The Angular application should have at least one starting main/root Module. This modular structure robust speed, you import only that module that you need.
Now create a folder
mkdir app or hover on directory name in VS Code’s explorer, you will see create new folder option
And create a new file main.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  imports:      [ BrowserModule ]
})
export class MainModule { }
This is actually entry point of the application. To run this application on browser it only need to import BrowserModule in imports array from @angular/platform-browser.

Now we need to add a Component to our app, it uses to control a part of a screen (view). An Angular application requires at least one component. It is basic building thing of Angular application.

app/main.component.ts

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


@Component({
  selector: 'helloworld-app',
  template: '<h2>Hello World!</h2>'
})
export class MainComponent { }
In above file import statement imports a @Component decorator from Angular's core. @Component decorator declares a class as an Angular component and provides metadata of configuration of component. The selector define CSS selector that gives the representation of the component in HTML element.

We add very simple Module and component for our tutorial for simplicity. In short, component class controls it view’s behaviour and appearance.

We add component to module that's why we use export before class keyword. Our update code is

app/main.module.ts

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


Add in NgModule decorator’s declarations and bootstrap fields.
Now in order to tell Angular how to start application, for this we add a file (main.ts) in app folder
app/main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { MainModule } from './main.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(MainModule);
This file initialize and use platforms in you application to bootstraps MainModule.
We keep three files, main module,main.ts,  and app component, separate for simplicity and reliability in testing and others.

Bootstraping is platform specific , it imports according to platform that’s why it is importing from @angular/platform-browser-dynamic
Now add index.html file that will host the application.

<html>
  <head>
    <title>Hello World Angular</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- Loading libraries form node_modules -->
    <script src="node_modules/core-js/client/shim.min.js"></script> <!-- Older browsers' polyfill -->
    <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- For loading module -->
    <script src="node_modules/zone.js/dist/zone.js"></script> <!-- Required by Angular -->
    <script src="node_modules/reflect-metadata/Reflect.js"></script> <!-- Required by Angular -->
    <script src="systemjs.config.js"></script>  <!-- SystemJS Configuration -->
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- Show application -->
  <body>
    <helloworld-app>Loading...</helloworld-app> <!-- Root/main component-->
  </body>
</html>
SystemJS: module loading library
reflect-metadata,zone.js required by Angular
core-js: provides ployfills (provide functionality of new browsers in older ones) for old browsers.
Systemjs.config.js: Configure SystemJS and run the app module by importing them those are referred in the main file.
Put you main component in body by adding <helloworld-app>.
We are done and ready to run Hello World

From terminal run
npm start
This command compile ts file in javascript and also deploy on lite-server, which load on browser and show changes instantly when change.

Now, you see a tab open on browser and display “Hello World!”.

You can add CSS to you application. Create styles.css file in directory. And add
/* Global/Master Style */
h2 {
  text-align: center;
  font-family: "Times New Roman", Times, serif;
}

No comments :

Post a Comment