Angular 2

Angular 2
An Angular 2 application have a root component that contains all other components. It is a component tree. 

It is a mobile first design. Data Flow from the server to browser is minimized. The framework itself is broken into a collection of modules, so that only the code needed to run the application is loaded.

Component pattern involves combining smaller, discrete blocks into larger finished products.

TypeScript

It is a super set of Java script, it is strongly typed, object oriented, compiled. It compiles to clean Java script which runs in any JavaScript engine that supports ECMA Script 3 or higher. 


What do decorators actually do in Angular 2?
Basically, decorators in Angular 2 apply metadata on classes


Angular2 Service




//1. Import all dependencies
import { Injectable } from '@angular/core';
import {Http, Response, RequestOptions, Headers} from '@angular/http';
import {Employee} from './employee.model';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
//2. The service class
@Injectable()
export class EmployeeService {
//3. The local private variable for  storing the URL of the REST API
private servUrl = "http://localhost:8020/EmployeeList/api/employees";
//4. Passsing the Http dependency to the constructor to access Http functions
constructor(private http: Http) { }
//5. Function to return the Observable response containing all Employees
getEmployees(): Observable<Response> {
    return this.http.get(this.servUrl);
}
//6. Function to perform POST operation to create a new employee
addEmployee(emp: Employee): Observable<Response> {
    let header = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: header });
    return this
        .http
        .post(this.servUrl, JSON.stringify(emp), options)
}
//7. Function to update Employee using PUT operation
updateEmployee(id: string, emp: Employee): Observable<Response> {
    let header = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: header });
    return this
        .http
        .put(this.servUrl + `/` + id, JSON.stringify(emp), options)
}
//8. Function to remove the Employee using DELETE operation
deleteEmployee(id: string): Observable<Response> {
    return this
        .http
        .delete(this.servUrl + `/` + id)
}
}


Angular 2 RC5 Sample

addhero.component.ts

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

@Component({
  selector: 'add-hero',
  template: `
    <input #newHero
      (keyup.enter)="addHero(newHero.value)"
      (blur)="addHero(newHero.value); newHero.value='' ">

    <button (click)="addHero(newHero.value)">Add</button>

    <ul><li *ngFor="let hero of heroes">{{hero}}</li></ul>
  `
})
export class AddHeroComponent {
  heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  addHero(newHero: string) {
    if (newHero) {
      this.heroes.push(newHero);
    }
  }
}

hero-parent.component.ts

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

import { HEROES } from './herolist';

@Component({
  selector: 'hero-parent',
  template: `
    <h2>{{master}} controls {{heroes.length}} heroes</h2>
    <hero-child *ngFor="let hero of heroes"
      [hero]="hero"
      [master]="master">
    </hero-child>
  `
})
export class HeroParentComponent {
  heroes = HEROES;
  master = 'Master';
}

hero-child.component.ts

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

import { Hero } from './herolist';

@Component({
  selector: 'hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  `
})
export class HeroChildComponent {
  @Input() hero: Hero;
  @Input('master') masterName: string;
}

hero.component.ts

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

import { Hero } from './hero';

@Component({
  selector: 'hero-app',
  templateUrl: './app/hero.component.html'
})
export class HeroComponent {
  title = 'Tour of Heroes';
  heroes = [
    new Hero(1, 'Windstorm'),
    new Hero(13, 'Bombasto'),
    new Hero(15, 'Magneta'),
    new Hero(20, 'Tornado')
  ];
  myHero = this.heroes[0];
}

hero.component.html

<body>
<h1 id="top">Component Communication Cookbook</h1>

<h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero.name}}</h2>
  <p>Heroes:</p>
  <ul>
    <li *ngFor="let hero of heroes">
      {{ hero.name }}
      </li>
  </ul>
  <p *ngIf="heroes.length > 3">There are many heroes!</p>
  <div id="parent-to-child">
  <hero-parent></hero-parent>
  </div>
  <div>
 <key-up></key-up>
  </div>
  <div>
 <add-hero></add-hero>
  </div>
  <div>
 <vote-taker></vote-taker>
  </div>
</body>

hero.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HeroComponent } from './hero.component';
import { HeroParentComponent } from './hero-parent.component';
import { HeroChildComponent } from './hero-child.component';
import {KeyUpComponent} from './keyup.component'
import {AddHeroComponent} from './addhero.component'
import {VoteTakerComponent} from './votetaker.component'
import {VoterComponent} from './voter.component'


let directives: any[] = [
 HeroComponent,
    //AppComponent,
    //AstronautComponent,
    //CountdownTimerComponent,
    HeroChildComponent,
    HeroParentComponent,
 KeyUpComponent,
 AddHeroComponent,
 VoteTakerComponent,
 VoterComponent
    //MissionControlComponent,
    //NameChildComponent,
    //NameParentComponent,
    //VersionChildComponent,
    //VersionParentComponent,
    //VoterComponent,
    //VoteTakerComponent
  ];

@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: directives,
  bootstrap: [HeroComponent]
})
export class HeroModule { }

hero.ts
export class Hero {
  constructor(
    public id: number,
    public name: string) { }
}

herolist.ts

export class Hero {
  name: string;
}

export const HEROES = [
  {name: 'Mr. IQ'},
  {name: 'Magneta'},
  {name: 'Bombasto'}
];

hero_main.ts

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

import { HeroModule } from './hero.module';

platformBrowserDynamic().bootstrapModule(HeroModule);

keyup.component.ts

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

@Component({
  selector: 'key-up',
  template: `
 <div>
  <label>Enter anything and press Enter:</label> 
  <input #box (keyup.enter)="onEnter(box.value)">
 </div>
    <p>{{value}}</p>
  `
})
export class KeyUpComponent{
  value = '';
  onEnter(value: string) { this.value = value; }
}

voter.component.ts

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'my-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="voted">Agree</button>
    <button (click)="vote(false)" [disabled]="voted">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() onVoted = new EventEmitter<boolean>();
  voted = false;

  vote(agreed: boolean) {
    this.onVoted.emit(agreed);
    this.voted = true;
  }
}

votertaker.component.ts

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

@Component({
  selector: 'vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
    <my-voter *ngFor="let voter of voters"
      [name]="voter"
      (onVoted)="onVoted($event)">
    </my-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];

  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Angular seed project</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 
  <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/typescript/lib/typescript.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <!-- script src="node_modules/rxjs/bundles/Rx.js"></script -->
  <script src="systemjs.config.js"></script>
  <script>
    //System.import('app').catch(function(err){ console.error(err); });
 System.import('app/hero_main').then(null, console.error.bind(console)) 
  </script>
</head>
 
<body>
<!--<app>Loading...</app>-->
<hero-app></hero-app>
</body>
</html>

package.json

{
  "name": "Angular2RC5",
  "description": "The current version of Angular is Release Candidate 5",
 "private": true,
  "scripts": {
   "start": "live-server"
  },
  "dependencies": {
 "@angular/common": "2.0.0-rc.5",
   "@angular/compiler": "2.0.0-rc.5",
   "@angular/core": "2.0.0-rc.5",
   "@angular/forms": "0.3.0",
   "@angular/http": "2.0.0-rc.5",
   "@angular/platform-browser": "2.0.0-rc.5",
   "@angular/platform-browser-dynamic": "2.0.0-rc.5",
   "@angular/router": "3.0.0-rc.1",
   "systemjs": "0.19.36",
   "core-js": "^2.4.0",
   "reflect-metadata": "^0.1.3",
   "rxjs": "5.0.0-beta.6",
   "zone.js": "^0.6.12",
   "angular2-in-memory-web-api": "0.0.15"
 },
 "devDependencies": {
   "live-server": "1.0.0",
   "typescript": "^2.0.0"
 }
}

systemjs.config.js

System.config({
    transpiler: 'typescript',
    typescriptOptions: {emitDecoratorMetadata: true},
    map: {
        'app' : 'app',
        'rxjs': 'node_modules/rxjs',
        '@angular'                    : 'node_modules/@angular'
      },
      packages: {
        'app'                              : {main: 'main', 
                                              defaultExtension: 'ts'},
        'rxjs'                             : {main: 'index.js'},
        '@angular/core'                    : {main: 'index.js'},
        '@angular/common'                  : {main: 'index.js'},
        '@angular/compiler'                : {main: 'index.js'},
        '@angular/router'                  : {main: 'index.js'},
        '@angular/platform-browser'        : {main: 'index.js'},
        '@angular/platform-browser-dynamic': {main: 'index.js'}
      }
});

Comments

Popular posts from this blog

WEB API

MVC