Saturday, 1 October 2016

Create a sample Angular 2 application with basic structure and setup for bootstrap using Typescript

In this post we are going to see the basic structure and setup for developing a angular2 single page application using Typescript, In angular2 lot of release are released by angular team, each and every release had lot of break through changes, even in the last release it have many changes from the Previous one, so we cant say which is correct way of development, each and every versions have different things in coding and setup. 


Now let we see what is the basic structure needed for develop a Angular 2 applications, in this sample we will use the Typescript for development. and we will create a Hello world sample.

First we will configure the basic things needed for project like configs.

Step 1. Setup the package.json
Step 2. Setup the tsconfig.json
Step 3. Setup the typings.json
Step 4. Create the systemjs.config.js
Step 5. Create the main.ts typescript file
Step 6. Run the npm
Step 7. Add the index.html file
Step 8. Create a component
Step 9. Create and Bootstrap a module
Step 10. Add the component in index.html and Start the npm

Now we create step by step


1. Setup the package.json, 

Create a folder name "angular applications", under that folder create a file package.json

 package.json
{
    "name": "Angular2",
    "description": "This projects deals with angular samples",
    "version": "1.0.0",
    "scripts": {
        "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
        "lite": "lite-server",
        "postinstall": "typings install",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "typings": "typings"
    },
    "dependencies": {
        "@angular/common": "~2.0.1",
        "@angular/compiler": "~2.0.1",
        "@angular/core": "~2.0.1",
        "@angular/forms": "~2.0.1",
        "@angular/http": "~2.0.1",
        "@angular/platform-browser": "~2.0.1",
        "@angular/platform-browser-dynamic": "~2.0.1",
        "@angular/router": "~3.0.1",
        "@angular/upgrade": "~2.0.1",
        "angular-in-memory-web-api": "~0.1.1",
        "bootstrap": "^3.3.7",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.8",
        "rxjs": "5.0.0-beta.12",
        "systemjs": "0.19.39",
        "zone.js": "^0.6.25"  
    },
    "devDependencies": {
         "concurrently": "^3.0.0",
         "lite-server": "^2.2.2",
         "typescript": "^2.0.3",
         "typings":"^1.4.0"
    }    
}


 In Above config you may find few key things, the important things are dependencies, devDependencies, scripts, in dependencies we have to add the dependent files which needs to download using the npm package manager, in devdependencies we have to configure additional things like server, typings, typescript version. In scripts section we can configure the postinstall settings and lite server inputs to compile and watch the files





2. Setup the tsconfig.json

Create a file name tsconfig,json , which is a configuration file used for typescript.

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





3. Setup the typings.json
    
Create a file named typings.json in which we can define additional typings

typings.json
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}





4. Create the systemjs.config.js

Now create a system config file which is used to define the basic things like module to be load by System.js, it is basically config file for System.js, Here we can define the paths and there bundles with short names which can be used through out the applications, Create a module pattern function inside that call a System.Config


systemjs.config.js
(function (global) {
    
    System.config({
        
        paths:{
            'npm:': 'node_modules/'
        },

        map: {
            // our app is within the app folder
            app: 'com',
            // 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 
    packages: {
            com: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
         }

    });

})(this);





5. Create the main.ts typescript file

Next important thing is we have to create main.ts file , Create a folder name com, then create a file name main.ts under that, Here we have to do the few important things , i.e bootstrap the module which is present under the application, if we have an component in index.html then the module in which it is present needs to be bootstrap, To bootstrap we have to create a platform specific bootstrap named   platformBrowserDynamic , using this we have to bootstrap the module

main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

const platform = platformBrowserDynamic();




6. Run the npm 

Now we have to install the packages using the npm, to do this first we have to install the node package manager in our system, then do the following steps.

  1. open the command prompt
  2. go to the root folder path of your application in your command prompt
  3. type npm install, which will install all packages includes in packages.json later it will run the post install the typings

Now node_modules are created inside your root folder.


7.  Add the index.html file

     Now we have to create a index.html file in the root folder which will load default in angular applications

<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="style.css">

    <!-- 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>
      
    <script src="lib/jquery.js"></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
  

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    
    <script>
      System.import('com').catch(function(err){ 
          console.error(err); 
        });
    </script>

  </head>
  <!-- 3. Display the application -->
  <body>
   
  </body>
</html>




8. Create a component

Next step is to create a component for our application , now we create a helloComponent, first create helloComponent.ts file under "com" folder

helloComponent.ts
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
    selector:'hello-app',
    template:'<h1>Hello {{name}}</h1>',
    encapsulation:ViewEncapsulation.None    
})
export class HelloComponent{
    name:string = "Rajesh G";
}





9. Create and Bootstrap a module

Next step is add the helloComponent to the HelloModule and bootstrap that module, Create a hello.module.ts file under the com folder

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { HelloComponent } from'./hello.component'

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

export class HelloModule{
    
}


Now add something configuration in the main.ts to bootstrap the module, adding the HelloModule in the bootstrap

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

const platform = platformBrowserDynamic();

let moduleref = platform.bootstrapModule(HelloModule);




10. Add the component in index.html and Start the npm

        Now we are adding that component in the index.html , inside the body tag

<body>
    <hello-app>Loading...</hello-app>
  </body>


then we have to start the server by following steps,Now run the npm package manager from command prompt

1. Go to the command prompt and iterate to the root folder of your application 
2. Type npm start which will start the server and load the application in browser.




Output:
**********************












From this post you can learn how to setup a basic Angular2 applications, still we can except many changes in stable releases also,to reach a well matured product phase.

No comments:

Post a Comment