Angular 2 is an open source JavaScript framework to build web applications in HTML and JavaScript and has been conceived as a mobile first approach.

Why to use Angular 2?

  • Angular 2 is simpler than Angular 1 and its fewer concepts make it easier to understand.
  • You can update the large data sets with minimal memory overhead.
  • It will speed up the initial load through server side rendering.

Features

  • Angular 2 is faster and easier than Angular 1.
  • It supports latest the version of browsers and also supports old browsers including IE9+ and Android 4.1+.
  • It is a cross platform framework.
  • Angular 2 is mainly focused on mobile apps.
  • Code structure is very simplified than the previous version of Angular.

Advantages

  • If an application is a heavy load, then Angular 2 keeps it fully UI responsive.
  • It uses server side rendering for fast views on mobile.
  • It works well with ECMAScript and other languages that compile to JavaScript.
  • It uses dependency injection to maintain applications without writing too long code.
  • Everything will be the component based approach.

Disadvantages

      • Since Angular 2 is a newly introduced framework, there is less online community support.
      • It takes time to learn if you are new to Angular 2.

To setup development environment follow the below steps:

Step1:

 mkdir angularjs2-test cd angularjs2-test

Step2:Creating Configuration Files:

We need to create tsconfig.json which is the TypeScript compiler configuration file. It guides the compiler to generate JavaScript files.

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Step(3): Create a typings.json file in your project folder angularjs2-test as shown below:

typings.json

{
  "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"
  }
}

A large number of libraries of the JavaScript extends JavaScript environment with features and syntax which is not natively recognized by the TypeScript compiler. The typings.json file is used to identify TypeScript definition files in your Angular application.

In the above code, there are three typing files as shown below:

      • core-js: It brings ES2015/ES6 capabilities to our ES5 browsers.
      • jasmine: It is the typing for Jasmine test framework.
      • node: It is used for the code that references objects in the nodejs environment.

These typings are used in development of larger Angular applications.

Step(4): Add package.json file to your angularjs2-test project folder with the below code:

package.json

{
  "name": "angularjs2-test",
  "version": "1.0.0",
  "scangular-2ripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.7",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.7.5",
    "typings":"^0.6.8"
  }
}

The package.json will contain the packages that our apps require. These packages are installed and maintained with npm (Node Package Manager).

Step(5): To install packages, run the below npm command in command prompt.

npm install

Error messages in red may appear while installing npm, just ignore them.

Creating Our First Angular Component

A component is the fundamental concept of Angular. A component is a class that controls a view template – a part of a web page where information to the user is displayed and user feedback is responded. Components are required to build Angular apps.

Step(6): Create a sub-folder called app/ inside your project folder to the place Angular app components. You can use the below command to create the folder:

mkdir app 
cd app

 

Step(7): The files which you create need to be saved with .ts extension. Create a file called environment_app.component.ts in your app/ folder with the below code:

environment_app.component.ts

import {Component, View} from "angular2/core";

@Component({
   selector: 'my-app'
})

@View({
  template: '

Step(8): Next, create environment_main.ts file with the below code:
environment_main.ts

import {bootstrap} from "angular2/platform/browser"
import {AppComponent} from "./environment_app.component"

bootstrap(AppComponent);
      • The environment_main.ts file tells Angular to load the component.
      • To launch the application, we need to import both Angular’s browser bootstrap function and root component of the application.
      • After importing, the bootstrap is called by passing the root component type i.e. AppComponent.

Step(9): Now create a index.html in your project folder angularjs2-test/ with the below code:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World</title>
     src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/
    es6-shim.min.js">
     src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/
    system-polyfills.js">
     src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js">
   
     src="https://code.angularjs.org/tools/system.js">
     src="https://code.angularjs.org/tools/typescript.js">
     src="https://code.angularjs.org/2.0.0-beta.6/Rx.js">
     src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js">
   
    
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}},
        map: { 'app': './angular2/src/app' }
      });
      System.import('app/environment_main')
            .then(null, console.error.bind(console));
    
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>
Loading …

Angular 2 – Architecture

The following daigram shows architecture of Angular 2:
angularjs2The architecture of Angular 2 contains following modules:

  • Module
  • Component
  • Template
  • Metadata
  • Data Binding
  • Service
  • Directive
  • Dependency Injection

Module

The module component is characterized by a block of code which can be used to perform a single task. You can export the value of something from the code such as a class. The Angular apps are called as modules and build your application using many modules. The basic building block of Angular 2 is a component class which can be exported from a module.

Some of the applications will have a component class name as AppComponent and you can find it in a file called app.component.ts. Use the export statement to export component class from module as shown below:

export class AppComponent { }

The export statement specifies that it is a module and its AppComponent class is defined as public and can be accessible to other modules of the application.

Component

A component is a controller class with a template which mainly deals with a view of the application and logic on the page. It is a bit of code that can be used throughout an application. Component knows how to render itself and configure dependency injection. You can associate CSS styles using component inline styles, style urls and template inline styles to a component.

To register component, we use @Component annotation and can be used to break up the application into smaller parts. There will be only one component per DOM element.

Template

The component’s view can be defined by using the template which tells Angular how to display the component. For instance, below simple template shows how to display the name:

Your name is : {{name}}

To display the value, you can put template expression within the interpolation braces.

Metadata

Metadata is a way of processing the class. Consider we have one component called MyComponent which will be a class until we tell Angular that it’s a component. You can use metadata to the class to tell Angular that MyComponent is a component. The metadata can be attached to TypeScript by using the decorator.

For instance:

@Component({
   selector : 'mylist',
   template : '<h2>Name is Harry</h2>'
   directives : [MyComponentDetails]
})
export class ListComponent{...}

The @Component is a decorator which uses configuration object to create the component and its view. The selector creates an instance of the component where it finds tag in parent HTML. The template tells Angular how to display the component. The directive decorator is used to represent the array of components or directives.

Data Binding

Data binding is a process of coordinating application data values by declaring bindings between sources and target HTML elements. It combines the template parts with components parts and template HTML is bound with markup to connect both sides. There are four types of data binding:

  • Interpolation: It displays the component value within the div tags.
  • Property Binding: It passes the property from the parent to property of the child.
  • Event Binding: It fires when you click on the components method name.
  • Two-way Binding: This form binds property and event by using thengModel directive in a single notation.

Service

Services are JavaScript functions that are responsible for doing a specific task only. Angular services are injected using Dependency Injection mechanism. Service includes the value, function or feature which is required by the application. Generally, service is a class which can perform something specific such as logging service, data service, message service, the configuration of application etc. There is nothing much about service in Angular and there is no ServiceBase class, but still services can be treated as fundamental to Angular application.

Directive

The directive is a class that represents the metadata. There are three types of directives:

  • Component Directive: It creates custom controller by using view and controller and used as custom HTML element.
  • Decorator Directive: It decorates the elements using additional behavior.
  • Template Directive: It converts HTML into a reusable template.

Dependency Injection

Dependency Injection is a design pattern that passes an object as dependencies in different components across the application. It creates new a instance of class along with its required dependencies.

You must remember the below points while using Dependency Injection:

The environment_main.ts file tells Angular to load the component.

To launch the application, we need to import both Angular’s browser bootstrap function and root component of the application.

After importing, the bootstrap is called by passing the root component type i.e. AppComponent.

  • The Dependency Injection is stimulated into the framework and can be used everywhere.
  • Theinjector mechanism maintains service instance and can be created using a provider.
  • Theprovider is a way of creating a service.
  • You can register theproviders along with injectors.