Angular 4.0 – Installation & Setup in Local Environment
Angular JS 28-Aug-2017

Angular 4.0 – Installation & Setup in Local Environment

For building Angular Application we can use many languages like JavaScript, ES5, ES2015(Known as ES6), Typescript, CoffeeScript and Dart (Non-JavaScript language). Typescript is the most commonly used language to develop Angular Applications.

Typescript is an open Source language and which is a superset of JavaScript. As the name says it is strongly typed and it has classes, interface, inheritance as like any object-oriented language. It gets converted to JavaScript which is supported by all the browsers.  You can find more information about Typescript in its official documentation.

If you are new to Angular you will be wondering how to start coding Angular Application. There are several ways you can do this,

 

Try Angular 4.0 on plunker without installing anything (QuickStart Example given in official Angular document)

Manually Installing Angular 4

In this post, we will see how to set up Angular 4 development environment manually. It is similar to Angular2 setup with few changes. Although we have many easy ways to start, it is always good to know manual method for better understanding

Step 1:  Install Node.js and npm

Node package manager(npm) is the command line utility that interacts with the repository of open source projects. It has become the package manager for JavaScript. Npm is distributed with Node.js, when you download Node.js you will automatically get npm installed on your computer. Get npm from this link.

When installation is complete we can run the below command to check version of node or npm installed.

node -v

If the installation is successful, you will get the below version number,

V7.9.0 (this may vary depends on the current version)

npm -v

 

If the installation is successful, you will get the below version number

4.5.0 (this may vary depends on the current version)

Angular 4.0 Installation

 

Step 2:  Choosing an Editor

Angular programming can be done with any code editor. You can choose any editors like Sublime Text, WebStorm, Atom, visual studio, visual studio code, eclipse. I’m using Visual studio code and you can install it from this link.

Once you have Installed node.js, npm, editor and a browser of your choice (I’m using chrome) we are ready to start our development.

Step 3:  Creating an Application Folder Structure

Angular 4.0 Folder Structure

Angular application folder structure will look as shown in this image.

Create the application folder as angularsetup (any name). Inside angularsetup folder, Create the folder src and inside ‘src’ folder create new folder app. Files outside src include configuration files and external dependency. Files inside src/ belong to your app typescript, HTML, CSS, and application specific features.

Step 4:  Creating package.json, bs-config.json, tsconfig.json, systemjs.config.js

package.json

Create new file package.json in application folder(angularsetup) and add the below configuration. Npm command will read the package config file and then install the required files into our application file path

{
  "name": "angular-setup-example",
  "version": "1.0.0",
  "private": true,
  "description": "Angular setup - example",
  "scripts": {
    "build": "tsc -p src/",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",  
    "build:watch": "tsc -p src/ -w",
    "build:upgrade": "tsc",
    "serve:upgrade": "http-server",
    "i18n": "ng-xi18n",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "dependencies": {
    "@angular/common": "~4.0.0",
    "@angular/compiler": "~4.0.0",
    "@angular/compiler-cli": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/forms": "~4.0.0",
    "@angular/http": "~4.0.0",
    "@angular/platform-browser": "~4.0.0",
    "@angular/platform-browser-dynamic": "~4.0.0",
    "@angular/platform-server": "~4.0.0",
    "@angular/router": "~4.0.0",
    "@angular/tsc-wrapped": "~4.0.0",
    "@angular/upgrade": "~4.0.0",
    "angular-in-memory-web-api": "~0.3.1",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "systemjs": "0.19.39",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@types/angular": "^1.5.16",
    "@types/angular-animate": "^1.5.5",
    "@types/angular-cookies": "^1.4.2",
    "@types/angular-mocks": "^1.5.5",
    "@types/angular-resource": "^1.5.6",
    "@types/angular-route": "^1.3.2",
    "@types/angular-sanitize": "^1.3.3",
    "@types/node": "^6.0.45",
    "canonical-path": "0.0.2",
    "concurrently": "^3.0.0",
    "http-server": "^0.9.0",
    "lite-server": "^2.2.2",
    "lodash": "^4.16.2",
    "source-map-explorer": "^1.3.2",
    "tslint": "^3.15.1",
    "typescript": "~2.2.0"
  },
  "repository": {}
}

package.json has the list of packages required for the angular application. It has three important sections,

  • Scripts: Script section will start the development server and typescript compiler from command line.
  • Dependencies: List of packages that application depend on to run. This contains angular libraries, polyfill libraries that add modern features to old browsers.
  • DevDependencies: This contains libraries that will be used only in development environment and will not be used after deployment.

bs-config.json

Create the lite-server configuration file (bs-config.json) in application folder and add the below configuration settings.

bs is browser sync and it serves the static content, detects changes, refreshes the browser, and offers many customizations. It will be useful for super-fast lightweight development

{
  "server": {
    "baseDir": "src",
    "routes": {
      "/node_modules": "node_modules"
    },
    "minify": false,
    "browser": "chrome"
  }
}

tsconfig.json

typescript requires a configuration file, create tsconfig.json in the ‘src’ folder and add the below configuration. We are writing our angular code in Typescript, but Browsers can’t execute Typescript directly. We can configure the Typescript compiler options and compile on save options to transpile .ts to .js files.

{
  "compilerOptions": {
    "target": "es5",//Setting ECMS script version to ES5
    "module": "commonjs", //generates our module in commonjs format.
    "moduleResolution": "node", 
    "sourceMap": true, //option to generate source map file.
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    //all types packages will be included.
    "typeRoots": [
      "../node_modules/@types/"
    ]
  },
  "compileOnSave": true, //to generate all the files for the tsconfig.json upon save.
  "exclude": [
    "node_modules"
    ] 
}

systemjs.config.js

Create new file systemjs.config.js inside src folder and add the below configuration. It is an ES module loader which loads all the files for our application. So, we don’t have to add script tag for every file we use in our application.

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      /*specifies the path where system files are located
        npm: is the alias for the path 'node_modules'
      */
      '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/animations': 'npm:@angular/animations/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@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/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.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/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.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',
        meta: {
          './*.js': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

 

tslint.json (optional)

Add new file tslint.json inside application folder and add the below rules.  tslint checks Typescript code for readability, maintainability, and functionality errors. Simply add the file to the root directory of the project. You should adjust rules to your needs

{
  "rules": {
    "class-name": true,
    "comment-format": [
      true,
      "check-space"
    ],
    "curly": true,
    "eofline": true,
    "forin": true,
    "indent": [
      true,
      "spaces"
    ],
    "label-position": true,
    "label-undefined": true,
    "max-line-length": [
      true,
      140
    ],
    "member-access": false,
    "member-ordering": [
      true,
      "static-before-instance",
      "variables-before-functions"
    ],
    "no-arg": true,
    "no-bitwise": true,
    "no-console": [
      true,
      "debug",
      "info",
      "time",
      "timeEnd",
      "trace"
    ],
    "no-construct": true,
    "no-debugger": true,
    "no-duplicate-key": true,
    "no-duplicate-variable": true,
    "no-empty": false,
    "no-eval": true,
    "no-inferrable-types": true,
    "no-shadowed-variable": true,
    "no-string-literal": false,
    "no-switch-case-fall-through": true,
    "no-trailing-whitespace": true,
    "no-unused-expression": true,
    "no-unused-variable": true,
    "no-unreachable": true,
    "no-use-before-declare": true,
    "no-var-keyword": true,
    "object-literal-sort-keys": false,
    "one-line": [
      true,
      "check-open-brace",
      "check-catch",
      "check-else",
      "check-whitespace"
    ],
    "quotemark": [
      true,
      "single"
    ],
    "radix": true,
    "semicolon": [
      "always"
    ],
    "triple-equals": [
      true,
      "allow-null-check"
    ],
    "typedef-whitespace": [
      true,
      {
        "call-signature": "nospace",
        "index-signature": "nospace",
        "parameter": "nospace",
        "property-declaration": "nospace",
        "variable-declaration": "nospace"
      }
    ],
    "variable-name": false,
    "whitespace": [
      true,
      "check-branch",
      "check-decl",
      "check-operator",
      "check-separator",
      "check-type"
    ]
  }
}

Systemjs-angular-loader.js (optional)

Create new file systemjs-angular-loader.js inside src folder and add the below configurations. This file is introduced in Angular 4.0, This plugin dynamically converts “component-relative” paths in templateUrl and styleUrls to “absolute paths“.

var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;

module.exports.translate = function(load){
  if (load.source.indexOf('moduleId') != -1) return load;

  var url = document.createElement('a');
  url.href = load.address;

  var basePathParts = url.pathname.split('/');

  basePathParts.pop();
  var basePath = basePathParts.join('/');

  var baseHref = document.createElement('a');
  baseHref.href = this.baseURL;
  baseHref = baseHref.pathname;

  if (!baseHref.startsWith('/base/')) { // it is not karma
    basePath = basePath.replace(baseHref, '');
  }

  load.source = load.source
    .replace(templateUrlRegex, function(match, quote, url){
      let resolvedUrl = url;

      if (url.startsWith('.')) {
        resolvedUrl = basePath + url.substr(1);
      }

      return 'templateUrl: "' + resolvedUrl + '"';
    })
    .replace(stylesRegex, function(match, relativeUrls) {
      var urls = [];

      while ((match = stringRegex.exec(relativeUrls)) !== null) {
        if (match[2].startsWith('.')) {
          urls.push('"' + basePath + match[2].substr(1) + '"');
        } else {
          urls.push('"' + match[2] + '"');
        }
      }

      return "styleUrls: [" + urls.join(', ') + "]";
    });

  return load;
};

Step 5: Installing the packages using “npm install”

Go to application folder (where package.json is available) in the command prompt and run the below command. It may install with some warnings but we can ignore it. Upon successful installation, you can find node_modules folder created in application folder. If you have existing, ‘node_modules’ folder in the application path below command will update the folder based configuration in package.json.

npm install

 

NPM Install

Step 6:  Creating Angular component and Angular module

Component

An Angular class responsible for exposing data to a view and handling most of the view’s display and user-interaction logic. The component is one of the most important building blocks in the Angular system.

AppComponent is the root component of the application. Common naming convention of the Angular component is to name the component with its feature name and append the word component as suffix. Those familiar with “MVC” and “MVVM” patterns will recognize the component in the role of “controller” or “view model“.

Create the file app.component.ts inside src\app\ folder and add the below code

//import the components which is used in this component.
import {Component} from "@angular/core";

//Component decorator- which has metadata that defines the template used by this component
@Component(
    {
        selector: "my-app",
        template:`
            <div>
                <h1 style="color:blue"> {{strName}} </h1>
                <div style="color:green"> My First Angular Component </div>
            </div>
            `
    }
)

//component class which has the methods and properties need by the view.
export class AppComponent{
    //string type property 
    strName:string ='Angular4 Setup Example'   
} 

Export keyword is used to export the class and make it used by the other components. Decorator is a function that adds metadata to class and its members. Selector is the directive name used in HTML. This is the custom HTML tag that can be used in html page to render this component’s template. All the component has templates which defines the layout or view managed by that component.

Module

Angular module is used to organize our application in to blocks of functionality and provides boundary within application. An Angular module identifies the components, directives, and pipes that the application uses along with the list of external Angular modules that the application needs. Every Angular application has an application root-module class. By convention, the class is called AppModule and resides in a file named app.module.ts.

Create the file app.module.ts inside src\app\ folder and add the below code

//importing the required modules from angular
import{NgModule} from "@angular/core";
import{BrowserModule} from "@angular/platform-browser";
//importing the component for this module
import{AppComponent} from "./app.component";

//Module decorator  
@NgModule({
    //To import external module that are used by all the components belong to this Module.
    imports:[BrowserModule],
    //array defines the component belongs to this module.
    declarations:[AppComponent],
    //root component of the application which contains selector in the index.html file
    bootstrap:[AppComponent]
})

//App module class. Root module of the application
export class AppModule {
}

Step 7:  Creating an Index.html and main.ts file

Create index.html file in src folder and add the below markup.

<html>
  <head>
    <title>Angular 4 Setup Application</title>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   
    <!--polyfills for older browser-->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <!--Angular uses zone for change detection and databinding-->
    <script src="node_modules/zone.js/dist/zone.min.js"></script>    

    <!--module Loader-->
    <script src="node_modules/systemjs/dist/system.src.js"></script>

   <!-- system configiration file-->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <!-- content managed by Angular -->
    <my-app></my-app>
  </body>
</html>

Create the main.ts file in the src folder and add the below code,

//Main Entry point of the application 
import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";
import {AppModule} from "./app/app.module"

//Angular compiler compiles the application in the browser and run the application from App module.
platformBrowserDynamic().bootstrapModule(AppModule); 

Step 8: Starting the server

All the basic setup has been done and now we will test our application, run the following command from the application root folder

npm start

 

This command starts the Typescript compiler and light-server development HTTP server and typescript compiler in watch mode. After running this command, new browser window will display our index.html page in localhost:3000

Whenever you do some changes to any files type script recompile them, the lite-server will refresh the browser automatically and reflect our changes immediately.

Angular 4.0 - Setup Example

How it Works?

Below picture showing the steps how Angular 4 project runs,

  1. html is setup to host the application by specifying the selector (my-app) inside the body tag.
  2. html imports and executes the main JavaScript file using systemjs.config.js file.
  3. ts is the main entry of the application, which bootstraps the applications Angular module ‘appmodule’.
  4. AppModule bootstraps the root component ‘appcomponent’ and the appcomponent’s template appears in the index.html page (inside selector tag) in the browser.

Note:  Typescript will generate equivalent .js and .map.js files for every .ts files which will be used by the browser to load the application.

Typescript will generate equivalent .js and .map.js files for every .ts files

Typescript will generate equivalent .js and .map.js files for every .ts files