SlideShare una empresa de Scribd logo
1 de 57
Descargar para leer sin conexión
Angular 2 for Java
Developers
Yakov Fain, Farata Systems
March 10, 2016
Angular 2
• Complete re-write of AngularJS
• Component-based
• Better performance
• No controllers, scopes
• Streamlined Dependency Injection
• Integrated RxJS
• Can write apps in TypeScript, 

Dart, or JavaScript (ES5 or ES6)
An app is a tree of components
HTML
A TypeScript class
HTML
Importing
modules
Class annotations
Project Structure
Config files
App dependencies
App code
{
Project Structure
SystemJS
transpiles
TS and
loads JS
bootstrap(ApplicationComponent)
Project Structure
bootstrap(ApplicationComponent)
Navigation with Router
import {Component} from 'angular2/core';

import {Product, ProductService} from 'app/services/product-service';
import CarouselComponent from '../carousel/carousel';

import ProductItemComponent from '../product-item/product-item';

import {ProductService} from '../../services/product-service';



@Component({

selector: 'auction-home-page',

directives: [

CarouselComponent,

ProductItemComponent

],

styleUrls: ['app/components/home/home.css'],

template: `

<div class="row carousel-holder">

<div class="col-md-12">

<auction-carousel></auction-carousel>

</div>

</div>

<div class="row">

<div *ngFor="#product of products" class="col-sm-4 col-lg-4 col
<auction-product-item [product]="product"></auction-product-i
</div>

</div>

`

})

export default class HomeComponent {

products: Product[] = [];



constructor(private productService: ProductService) {

this.products = this.productService.getProducts();

}

}

Exporing a

module
HomeComponent
Importing

Modules
Dependency
Injection
HomeComponent
import {Component} from 'angular2/core';

import {Product, ProductService} from 'app/services/product-service';
import CarouselComponent from '../carousel/carousel';

import ProductItemComponent from '../product-item/product-item';

import {ProductService} from '../../services/product-service';



@Component({

selector: 'auction-home-page',

directives: [

CarouselComponent,

ProductItemComponent

],

styleUrls: ['app/components/home/home.css'],

template: `

<div class="row carousel-holder">

<div class="col-md-12">

<auction-carousel></auction-carousel>

</div>

</div>

<div class="row">

<div *ngFor="#product of products" class="col-sm-4 col-lg-4 col
<auction-product-item [product]="product"></auction-product-i
</div>

</div>

`

})

export default class HomeComponent {

products: Product[] = [];



constructor(private productService: ProductService) {

this.products = this.productService.getProducts();

}

}

import {Component} from 'angular2/core';

import {Product, ProductService} from 'app/services/product-service';
import CarouselComponent from '../carousel/carousel';

import ProductItemComponent from '../product-item/product-item';

import {ProductService} from '../../services/product-service';



@Component({

selector: 'auction-home-page',

directives: [

CarouselComponent,

ProductItemComponent

],

styleUrls: ['app/components/home/home.css'],

template: `

<div class="row carousel-holder">

<div class="col-md-12">

<auction-carousel></auction-carousel>

</div>

</div>

<div class="row">

<div *ngFor="#product of products" class="col-sm-4 col-lg-4 col
<auction-product-item [product]="product"></auction-product-i
</div>

</div>

`

})

export default class HomeComponent {

products: Product[] = [];



constructor(private productService: ProductService) {

this.products = this.productService.getProducts();

}

}

Looping with *ngFor
A Sample Toolbox
Intro to TypeScript
http://www.typescriptlang.org
What’s TypeScript?
• An open-source language developed by Microsoft
• Designed by Anders Hejlsberg, the creator of C#, Delphi,
and Turbo Pascal
• A superset of JavaScript
• Well supported by IDEs
Benefits of Writing in TypeScript
• Increases your productivity in producing JavaScript
• Supports types, classes, interfaces, generics, annotations
• Compiles into a human-readable JavaScript
• Easy to learn by Java developers
• Supports most of the ES6 and some ES7 syntax
Transpiling TypeScript Interactively

http://www.typescriptlang.org/Playground
TypeScript JavaScript (E5)
Classes
TypeScript JavaScript (E5)
A Class With Constructor
TypeScript JavaScript (E5)
Inheritance
Classical syntax Prototypal
Generics
Error
No Errors
Arrow Function Expressions (lambdas)
var getName = () => 'John Smith';
console.log(`The name is ` + getName());
Interfaces as Custom Types
Interfaces and implements
TypeScript Compiler: tsc
• Install the typescript compiler with npm (comes with Node.js):



npm install -g typescript
• Compile main.ts into main.js specifying target language syntax:



tsc —t ES5 main.ts
• Usually the compiler’s options are set in tsconfig.json file
• The watch mode allows to auto-compile as files change:



tsc -w *.ts
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
@Component({
selector: 'hello-world',
template: '<h1>Hello {{ name }}!</h1>'
})
class HelloWorldComponent {
name: string;
constructor() {
this.name = ‘World!';
}
}
bootstrap(HelloWorldComponent);
HelloWorldComponent in Angular
In HTML:



<hello-world></hello-world>
SystemJS: a Universal Module Loader
• ES6 defines modules, but not the loader
• ES7 should include the System object for loading
modules
• SystemJS is a polyfill that loads modules
Index.html Take 1
<!DOCTYPE html>
<html>
<head>
<script src="//npmcdn.com/angular2@2.0.0-beta.7/bundles/angular2-polyfills.js"></script>
<script src="//npmcdn.com/typescript@1.7.5/lib/typescript.js"></script>
<script src="//npmcdn.com/systemjs@0.19.22/dist/system.src.js"></script>
<script src="//npmcdn.com/rxjs@5.0.0-beta.2/bundles/Rx.js"></script>
<script src="//npmcdn.com/angular2@2.0.0-beta.7/bundles/angular2.dev.js"></script>


<script>
System.config({
transpiler: 'typescript',
typescriptOptions: {emitDecoratorMetadata: true}
});
System.import('main.ts');
</script>
</head>
<body>
<hello-world></hello-world>
</body>
</html>
Angular from CDN
SystemJS
HelloWorldComponent
Starting a new project with npm
1. Generate package.json for your project:

npm init -y
2. Add Angular dependencies to package.json
3. Download dependencies into the dir node_modules: 

npm install
4. Install live-server

npm install live-server -g
package.json
{
"name": "walkthrough5",
"version": "1.0.0",
"description": “A sample package.json for the Angular app”,
"scripts": {
"start": "live-server"
},
"dependencies": {
"es6-shim": "0.33.13",
"es6-promise": "^3.0.2",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"systemjs": "0.19.23",
"zone.js": "0.5.15",
"angular2": "2.0.0-beta.9"
},


"devDependencies": {
"live-server": "^0.9.0",
"typescript": "^1.7.5"
}
}
<!DOCTYPE html>
<html>
<head>
<script src="node_modules/angular2/bundles/angular2-polyfills.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="node_modules/angular2/bundles/angular2.dev.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: {emitDecoratorMetadata: true}
});
System.import('main.ts');
</script>
</head>
<body>
<hello-world></hello-world>
</body>
</html>
Index.html Take 2
Angular’s local (after npm install)
Templates
• A place to write HTML
• Rendering is separated from the core framework
• Angular team works with Telerik on rendering for iOS and Android using NativeScript
@Component({

selector: 'auction-home-page',

…

styleUrls: ['app/components/home/home.css'],

template: `

<div class="row carousel-holder">

<div class="col-md-12">

<auction-carousel></auction-carousel>

</div>

</div>

<div class="row">

<div class="col-md-12">

<div class="form-group">

<input placeholder="Filter products by title” type="text">

</div>

</div>

</div>

`

})
Unidirectional Binding
From code to template:
<h1>Hello {{ name }}!</h1>
<span [hidden]=“isZipcodeValid”>Zip code is not valid</span>
From template to code:
<button (click)="placeBid()">Place Bid</button>
<input placeholder= "Product name" (input)="onInputEvent()">
Two-way Binding
Synchronizing Model and View:
<input [value]="myComponentProperty" 

(input)=“onInputEvent($event)>
<input [(ngModel)] = "myComponentProperty">
Dependency Injection
• Angular can create services; no need to use the new
operator
• Angular injects objects into components via constructors only
• Each component has an injector
• Providers specify how to inject
• If a component has no provider defined, Angular checks its
parent
product-service.ts
export class Product {

constructor(

public id: number,

public title: string,

public price: number,

public description: string) {

}

}



export class ProductService {

getProduct(): Product {

return new Product( 0, "iPhone 7", 249.99,
"The latest iPhone, 7-inch screen");

}

}
Injecting ProductService
import {Component, bind} from 'angular2/core';

import {ProductService, Product} from "../services/product-service";



@Component({

selector: 'di-product-page',

template: `<div>

<h1>Product Details</h1>

<h2>Title: {{product.title}}</h2>

<h2>Description: {{product.description}}</h2>

<h2>Price: ${{product.price}}</h2>

</div>`,

providers:[ProductService]

})



export default class ProductComponent {

product: Product;



constructor( productService: ProductService) {



this.product = productService.getProduct();

}

}

A provider can be a
class, factory, or a value
Injection
Injecting Dependencies of Dependencies
Injecting Dependencies of Dependencies
import {Http} from 'angular2/http';
@Injectable
export class ProductService {
constructor(private http:Http){
let products = http.get('products.json');
}
…
}
Routing Bulding Blocks
• RouterOutlet (<router-outlet>) - where the router should render the component
• @RouteConfig - map URLs to components to be rendered inside the <router-outlet>
• RouterLink ([routerLink]) - a link to a named route.
• RouteParams - a map of key-value pairs to pass parameters to the route
• RouteData - a map of key-value pairs used to pass additional data from
@RouteConfig to a route
@Component({

selector: ‘basic-routing',


template: `<a [routerLink]="['/Home']">Home</a>

<a [routerLink]="['/ProductDetail']">Product Details</a>

<router-outlet></router-outlet>`,

directives: [ ROUTER_DIRECTIVES]

})



@RouteConfig([

{path: '/', component: HomeComponent, as: 'Home'},

{path: '/product', component: ProductDetailComponent, as: 'ProductDetail'}

])

class RootComponent{

}



bootstrap(RootComponent, [ROUTER_PROVIDERS, provide(LocationStrategy,

{useClass: HashLocationStrategy})]);
Basic Routing
@Component({

selector: 'basic-routing',

template: `<a [routerLink]="['/Home']">Home</a>

<a [routerLink]="['/ProductDetail',
{id:1234}]">Product Details</a>

<router-outlet></router-outlet>`,

directives: [ ROUTER_DIRECTIVES]

})

@RouteConfig([

{path: '/', component: HomeComponent, as: 'Home'},



{path: '/product/:id', component: ProductDetailComponent, 

as: 'ProductDetail'}



])

class RootComponent{}



bootstrap(RootComponent, [ROUTER_PROVIDERS,

provide(LocationStrategy, {useClass: HashLocationStrategy})]);
Passing Data to a Route
@Component({

selector: ‘product',


template: `<h1 class="product">Product Detail for Product: 

{{productID}}</h1>`,


styles: ['product {background: cyan}']

})


export class ProductDetailComponent {

productID: string;
constructor(params: RouteParams){



this.productID = params.get('id');

}

}
Receiving Data in a Route
1
2
3
Reactive Programming
• Angular comes with RxJS library of reactive extensions

• A observable stream emits the data over time to the
subscriber.
• Supports multiple operators to transform the stream’s data

• Stream samples: 

- UI events

- HTTP responses

- Data arriving over websockets
Observable Streams
• Emit the next element
• Throw an error
• Send a signal that the streaming is over
An observable stream can:
Observers
• A function to handle streaming object
• Error handling
• End-of-stream handling
An observer provides:
Transforming the stream
Observables vs Promises
• Observable can return multiple values
• Observables can be cancelled
• Observables allow to handle end-of-stream
Observable Events@Component({

selector: "app",

template: `

<h2>Observable events demo</h2>

<input type="text" placeholder="Enter stock" [ngFormControl]="searchInput">

`

})

class AppComponent {



searchInput: Control;



constructor(){

this.searchInput = new Control('');



this.searchInput.valueChanges

.debounceTime(500)

.subscribe(stock => this.getStockQuoteFromServer(stock));

}



getStockQuoteFromServer(stock) {



console.log(`The price of ${stock} is ${100*Math.random().toFixed(4)}`);

}

}
Observable
Http and Observables


class AppComponent {



products: Array<string> = [];



constructor(private http: Http) {



this.http.get(‘http://localhost:8080/products')

.map(res => res.json())

.subscribe(

data => {



this.products=data;

},



err =>

console.log("Can't get products. Error code: %s, URL: %s ",

err.status, err.url),



() => console.log('Product(s) are retrieved')

);

}

}
DI
O
b
s
e
r
v
e
r
Deployment
• We use Webpack bundler for packaging
• npm scripts for running the build scripts
The app
index.html
Frameworks
Preparing deployment with Webpack
• Input: the entry point(s) of your app
• Output: transpiled bundle (a .js file)
• Resources (css, images, html) can be inlined in the bundle
• Usually, the app will have at least two bundles:



- your code (e.g. bundle.js)



- frameworks and libraries (e.g. vendor.bundle.js)
Webpack Loaders & Plugins
• Loaders operate on a single file (e.g. transpile TS into JS)
• Plugins can operate on multiple files and be invoked at
different stages of the Webpack lifecycle
…
module.exports = {

debug: false,

devtool: 'source-map',

entry: {

'main' : './src/main.ts',

'vendor': './src/vendor.ts'

},

metadata: metadata,

module: {

loaders: [

{test: /.css$/, loader: 'to-string!css'},

{test: /.html$/, loader: 'raw'},

{test: /.ts$/, loader: 'ts'}

],

noParse: [path.join(__dirname, 'node_modules', 'angular2', 'bundles')]

},

output: {

path : './dist',

filename: 'bundle.js'

},

plugins: [

new CommonsChunkPlugin({name: 'vendor', filename: 'vendor.bundle.js', minChunks: Infinity}),

new CompressionPlugin({regExp: /.css$|.html$|.js$|.map$/, threshold: 1500}),

new CopyWebpackPlugin([{from: './src/index.html', to: 'index.html'}]),

new DedupePlugin(),

new DefinePlugin({'webpack': {'ENV': JSON.stringify(metadata.ENV)}}),

new OccurenceOrderPlugin(true),

new UglifyJsPlugin({

compress : {screw_ie8 : true},

mangle: {

screw_ie8 : true,

except: ['RouterLink'] // TODO: Remove after #6678 fixed

}

})

],

resolve: {

extensions: ['', '.ts', '.js']

}

webpack.config.js
npm scripts in package.json
"scripts": {



"clean": "rimraf dist",



"postinstall": "typings install",



"prebuild": "npm run clean",

"build": "webpack --config webpack.prod.config.js --progress —profile --display-cached",



"start": "webpack-dev-server --inline --progress --display-cached --port 8080",



"preserve:dist": "npm run build",

"serve:dist": "static dist -z"

}
To run a script from the command line:



npm start
or
npm run build
or
npm run serve:dist
Links
• A two-day Angular 2 workshop, March 28-29, 2016, New York,

http://bit.ly/1R0FAhN 

discount code: jugmember
• Angular consulting/training: faratasystems.com
• Blog: yakovfain.com
• Our book: http://bit.ly/1QYeqL0




Más contenido relacionado

La actualidad más candente

Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Sumanth Chinthagunta
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersPaweł Żurowski
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next FrameworkCommit University
 
Angular elements - embed your angular components EVERYWHERE
Angular elements - embed your angular components EVERYWHEREAngular elements - embed your angular components EVERYWHERE
Angular elements - embed your angular components EVERYWHERENadav Mary
 
Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Yakov Fain
 
Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6William Marques
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersOswald Campesato
 
Developing a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2IDeveloping a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2INader Debbabi
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core conceptsCodemotion
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppKaty Slemon
 
What’s new in angular 2
What’s new in angular 2What’s new in angular 2
What’s new in angular 2Ran Wahle
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTYakov Fain
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?jbandi
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2Dor Moshe
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 

La actualidad más candente (20)

Angular 2
Angular 2Angular 2
Angular 2
 
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0
 
Angular 5
Angular 5Angular 5
Angular 5
 
Introduction to angular 4
Introduction to angular 4Introduction to angular 4
Introduction to angular 4
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developers
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
An Overview of Angular 4
 
Angular elements - embed your angular components EVERYWHERE
Angular elements - embed your angular components EVERYWHEREAngular elements - embed your angular components EVERYWHERE
Angular elements - embed your angular components EVERYWHERE
 
Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020Type script for_java_dev_jul_2020
Type script for_java_dev_jul_2020
 
Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
Developing a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2IDeveloping a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2I
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core concepts
 
React native
React nativeReact native
React native
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
What’s new in angular 2
What’s new in angular 2What’s new in angular 2
What’s new in angular 2
 
RESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoTRESTful services and OAUTH protocol in IoT
RESTful services and OAUTH protocol in IoT
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 

Similar a Angular 2 for Java Developers

Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architectureJasper Moelker
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSAlberto Paro
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsScala Italy
 
Developing Lightning Components for Communities.pptx
Developing Lightning Components for Communities.pptxDeveloping Lightning Components for Communities.pptx
Developing Lightning Components for Communities.pptxDmitry Vinnik
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Ahmed Moawad
 
Migrating an Application from Angular 1 to Angular 2
Migrating an Application from Angular 1 to Angular 2 Migrating an Application from Angular 1 to Angular 2
Migrating an Application from Angular 1 to Angular 2 Ross Dederer
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSYoann Gotthilf
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedGil Fink
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN StackTroy Miles
 

Similar a Angular 2 for Java Developers (20)

mean stack
mean stackmean stack
mean stack
 
The MEAN stack
The MEAN stack The MEAN stack
The MEAN stack
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
 
Angular 2 - a New Hope
Angular 2 - a New HopeAngular 2 - a New Hope
Angular 2 - a New Hope
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Developing Lightning Components for Communities.pptx
Developing Lightning Components for Communities.pptxDeveloping Lightning Components for Communities.pptx
Developing Lightning Components for Communities.pptx
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1
 
Angular IO
Angular IOAngular IO
Angular IO
 
Migrating an Application from Angular 1 to Angular 2
Migrating an Application from Angular 1 to Angular 2 Migrating an Application from Angular 1 to Angular 2
Migrating an Application from Angular 1 to Angular 2
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has Arrived
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN Stack
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 

Más de Yakov Fain

Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in AngularYakov Fain
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2Yakov Fain
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2Yakov Fain
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Yakov Fain
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowYakov Fain
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web ApplicationYakov Fain
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual CompanyYakov Fain
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_githubYakov Fain
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software DeveloperYakov Fain
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developerYakov Fain
 

Más de Yakov Fain (16)

Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Integrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business WorkflowIntegrating consumers IoT devices into Business Workflow
Integrating consumers IoT devices into Business Workflow
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Running a Virtual Company
Running a Virtual CompanyRunning a Virtual Company
Running a Virtual Company
 
Princeton jug git_github
Princeton jug git_githubPrinceton jug git_github
Princeton jug git_github
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Surviving as a Professional Software Developer
Surviving as a Professional Software DeveloperSurviving as a Professional Software Developer
Surviving as a Professional Software Developer
 
Becoming a professional software developer
Becoming a professional software developerBecoming a professional software developer
Becoming a professional software developer
 

Último

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 

Último (20)

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 

Angular 2 for Java Developers

  • 1. Angular 2 for Java Developers Yakov Fain, Farata Systems March 10, 2016
  • 2. Angular 2 • Complete re-write of AngularJS • Component-based • Better performance • No controllers, scopes • Streamlined Dependency Injection • Integrated RxJS • Can write apps in TypeScript, 
 Dart, or JavaScript (ES5 or ES6)
  • 3. An app is a tree of components
  • 7. Project Structure Config files App dependencies App code {
  • 8. Project Structure SystemJS transpiles TS and loads JS bootstrap(ApplicationComponent)
  • 11. import {Component} from 'angular2/core';
 import {Product, ProductService} from 'app/services/product-service'; import CarouselComponent from '../carousel/carousel';
 import ProductItemComponent from '../product-item/product-item';
 import {ProductService} from '../../services/product-service';
 
 @Component({
 selector: 'auction-home-page',
 directives: [
 CarouselComponent,
 ProductItemComponent
 ],
 styleUrls: ['app/components/home/home.css'],
 template: `
 <div class="row carousel-holder">
 <div class="col-md-12">
 <auction-carousel></auction-carousel>
 </div>
 </div>
 <div class="row">
 <div *ngFor="#product of products" class="col-sm-4 col-lg-4 col <auction-product-item [product]="product"></auction-product-i </div>
 </div>
 `
 })
 export default class HomeComponent {
 products: Product[] = [];
 
 constructor(private productService: ProductService) {
 this.products = this.productService.getProducts();
 }
 }
 Exporing a
 module HomeComponent Importing
 Modules
  • 12. Dependency Injection HomeComponent import {Component} from 'angular2/core';
 import {Product, ProductService} from 'app/services/product-service'; import CarouselComponent from '../carousel/carousel';
 import ProductItemComponent from '../product-item/product-item';
 import {ProductService} from '../../services/product-service';
 
 @Component({
 selector: 'auction-home-page',
 directives: [
 CarouselComponent,
 ProductItemComponent
 ],
 styleUrls: ['app/components/home/home.css'],
 template: `
 <div class="row carousel-holder">
 <div class="col-md-12">
 <auction-carousel></auction-carousel>
 </div>
 </div>
 <div class="row">
 <div *ngFor="#product of products" class="col-sm-4 col-lg-4 col <auction-product-item [product]="product"></auction-product-i </div>
 </div>
 `
 })
 export default class HomeComponent {
 products: Product[] = [];
 
 constructor(private productService: ProductService) {
 this.products = this.productService.getProducts();
 }
 }

  • 13. import {Component} from 'angular2/core';
 import {Product, ProductService} from 'app/services/product-service'; import CarouselComponent from '../carousel/carousel';
 import ProductItemComponent from '../product-item/product-item';
 import {ProductService} from '../../services/product-service';
 
 @Component({
 selector: 'auction-home-page',
 directives: [
 CarouselComponent,
 ProductItemComponent
 ],
 styleUrls: ['app/components/home/home.css'],
 template: `
 <div class="row carousel-holder">
 <div class="col-md-12">
 <auction-carousel></auction-carousel>
 </div>
 </div>
 <div class="row">
 <div *ngFor="#product of products" class="col-sm-4 col-lg-4 col <auction-product-item [product]="product"></auction-product-i </div>
 </div>
 `
 })
 export default class HomeComponent {
 products: Product[] = [];
 
 constructor(private productService: ProductService) {
 this.products = this.productService.getProducts();
 }
 }
 Looping with *ngFor
  • 16. What’s TypeScript? • An open-source language developed by Microsoft • Designed by Anders Hejlsberg, the creator of C#, Delphi, and Turbo Pascal • A superset of JavaScript • Well supported by IDEs
  • 17. Benefits of Writing in TypeScript • Increases your productivity in producing JavaScript • Supports types, classes, interfaces, generics, annotations • Compiles into a human-readable JavaScript • Easy to learn by Java developers • Supports most of the ES6 and some ES7 syntax
  • 20. A Class With Constructor TypeScript JavaScript (E5)
  • 23. Arrow Function Expressions (lambdas) var getName = () => 'John Smith'; console.log(`The name is ` + getName());
  • 26. TypeScript Compiler: tsc • Install the typescript compiler with npm (comes with Node.js):
 
 npm install -g typescript • Compile main.ts into main.js specifying target language syntax:
 
 tsc —t ES5 main.ts • Usually the compiler’s options are set in tsconfig.json file • The watch mode allows to auto-compile as files change:
 
 tsc -w *.ts
  • 27. import {bootstrap} from 'angular2/platform/browser'; import {Component} from 'angular2/core'; @Component({ selector: 'hello-world', template: '<h1>Hello {{ name }}!</h1>' }) class HelloWorldComponent { name: string; constructor() { this.name = ‘World!'; } } bootstrap(HelloWorldComponent); HelloWorldComponent in Angular In HTML:
 
 <hello-world></hello-world>
  • 28. SystemJS: a Universal Module Loader • ES6 defines modules, but not the loader • ES7 should include the System object for loading modules • SystemJS is a polyfill that loads modules
  • 29. Index.html Take 1 <!DOCTYPE html> <html> <head> <script src="//npmcdn.com/angular2@2.0.0-beta.7/bundles/angular2-polyfills.js"></script> <script src="//npmcdn.com/typescript@1.7.5/lib/typescript.js"></script> <script src="//npmcdn.com/systemjs@0.19.22/dist/system.src.js"></script> <script src="//npmcdn.com/rxjs@5.0.0-beta.2/bundles/Rx.js"></script> <script src="//npmcdn.com/angular2@2.0.0-beta.7/bundles/angular2.dev.js"></script> 
 <script> System.config({ transpiler: 'typescript', typescriptOptions: {emitDecoratorMetadata: true} }); System.import('main.ts'); </script> </head> <body> <hello-world></hello-world> </body> </html> Angular from CDN SystemJS HelloWorldComponent
  • 30. Starting a new project with npm 1. Generate package.json for your project:
 npm init -y 2. Add Angular dependencies to package.json 3. Download dependencies into the dir node_modules: 
 npm install 4. Install live-server
 npm install live-server -g
  • 31. package.json { "name": "walkthrough5", "version": "1.0.0", "description": “A sample package.json for the Angular app”, "scripts": { "start": "live-server" }, "dependencies": { "es6-shim": "0.33.13", "es6-promise": "^3.0.2", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.2", "systemjs": "0.19.23", "zone.js": "0.5.15", "angular2": "2.0.0-beta.9" }, 
 "devDependencies": { "live-server": "^0.9.0", "typescript": "^1.7.5" } }
  • 32. <!DOCTYPE html> <html> <head> <script src="node_modules/angular2/bundles/angular2-polyfills.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="node_modules/angular2/bundles/angular2.dev.js"></script> <script> System.config({ transpiler: 'typescript', typescriptOptions: {emitDecoratorMetadata: true} }); System.import('main.ts'); </script> </head> <body> <hello-world></hello-world> </body> </html> Index.html Take 2 Angular’s local (after npm install)
  • 33. Templates • A place to write HTML • Rendering is separated from the core framework • Angular team works with Telerik on rendering for iOS and Android using NativeScript @Component({
 selector: 'auction-home-page',
 …
 styleUrls: ['app/components/home/home.css'],
 template: `
 <div class="row carousel-holder">
 <div class="col-md-12">
 <auction-carousel></auction-carousel>
 </div>
 </div>
 <div class="row">
 <div class="col-md-12">
 <div class="form-group">
 <input placeholder="Filter products by title” type="text">
 </div>
 </div>
 </div>
 `
 })
  • 34. Unidirectional Binding From code to template: <h1>Hello {{ name }}!</h1> <span [hidden]=“isZipcodeValid”>Zip code is not valid</span> From template to code: <button (click)="placeBid()">Place Bid</button> <input placeholder= "Product name" (input)="onInputEvent()">
  • 35. Two-way Binding Synchronizing Model and View: <input [value]="myComponentProperty" 
 (input)=“onInputEvent($event)> <input [(ngModel)] = "myComponentProperty">
  • 36. Dependency Injection • Angular can create services; no need to use the new operator • Angular injects objects into components via constructors only • Each component has an injector • Providers specify how to inject • If a component has no provider defined, Angular checks its parent
  • 37. product-service.ts export class Product {
 constructor(
 public id: number,
 public title: string,
 public price: number,
 public description: string) {
 }
 }
 
 export class ProductService {
 getProduct(): Product {
 return new Product( 0, "iPhone 7", 249.99, "The latest iPhone, 7-inch screen");
 }
 }
  • 38. Injecting ProductService import {Component, bind} from 'angular2/core';
 import {ProductService, Product} from "../services/product-service";
 
 @Component({
 selector: 'di-product-page',
 template: `<div>
 <h1>Product Details</h1>
 <h2>Title: {{product.title}}</h2>
 <h2>Description: {{product.description}}</h2>
 <h2>Price: ${{product.price}}</h2>
 </div>`,
 providers:[ProductService]
 })
 
 export default class ProductComponent {
 product: Product;
 
 constructor( productService: ProductService) {
 
 this.product = productService.getProduct();
 }
 }
 A provider can be a class, factory, or a value Injection
  • 40. Injecting Dependencies of Dependencies import {Http} from 'angular2/http'; @Injectable export class ProductService { constructor(private http:Http){ let products = http.get('products.json'); } … }
  • 41. Routing Bulding Blocks • RouterOutlet (<router-outlet>) - where the router should render the component • @RouteConfig - map URLs to components to be rendered inside the <router-outlet> • RouterLink ([routerLink]) - a link to a named route. • RouteParams - a map of key-value pairs to pass parameters to the route • RouteData - a map of key-value pairs used to pass additional data from @RouteConfig to a route
  • 42. @Component({
 selector: ‘basic-routing', 
 template: `<a [routerLink]="['/Home']">Home</a>
 <a [routerLink]="['/ProductDetail']">Product Details</a>
 <router-outlet></router-outlet>`,
 directives: [ ROUTER_DIRECTIVES]
 })
 
 @RouteConfig([
 {path: '/', component: HomeComponent, as: 'Home'},
 {path: '/product', component: ProductDetailComponent, as: 'ProductDetail'}
 ])
 class RootComponent{
 }
 
 bootstrap(RootComponent, [ROUTER_PROVIDERS, provide(LocationStrategy,
 {useClass: HashLocationStrategy})]); Basic Routing
  • 43. @Component({
 selector: 'basic-routing',
 template: `<a [routerLink]="['/Home']">Home</a>
 <a [routerLink]="['/ProductDetail', {id:1234}]">Product Details</a>
 <router-outlet></router-outlet>`,
 directives: [ ROUTER_DIRECTIVES]
 })
 @RouteConfig([
 {path: '/', component: HomeComponent, as: 'Home'},
 
 {path: '/product/:id', component: ProductDetailComponent, 
 as: 'ProductDetail'}
 
 ])
 class RootComponent{}
 
 bootstrap(RootComponent, [ROUTER_PROVIDERS,
 provide(LocationStrategy, {useClass: HashLocationStrategy})]); Passing Data to a Route
  • 44. @Component({
 selector: ‘product', 
 template: `<h1 class="product">Product Detail for Product: 
 {{productID}}</h1>`, 
 styles: ['product {background: cyan}']
 }) 
 export class ProductDetailComponent {
 productID: string; constructor(params: RouteParams){
 
 this.productID = params.get('id');
 }
 } Receiving Data in a Route 1 2 3
  • 45. Reactive Programming • Angular comes with RxJS library of reactive extensions
 • A observable stream emits the data over time to the subscriber. • Supports multiple operators to transform the stream’s data
 • Stream samples: 
 - UI events
 - HTTP responses
 - Data arriving over websockets
  • 46. Observable Streams • Emit the next element • Throw an error • Send a signal that the streaming is over An observable stream can:
  • 47. Observers • A function to handle streaming object • Error handling • End-of-stream handling An observer provides:
  • 49. Observables vs Promises • Observable can return multiple values • Observables can be cancelled • Observables allow to handle end-of-stream
  • 50. Observable Events@Component({
 selector: "app",
 template: `
 <h2>Observable events demo</h2>
 <input type="text" placeholder="Enter stock" [ngFormControl]="searchInput">
 `
 })
 class AppComponent {
 
 searchInput: Control;
 
 constructor(){
 this.searchInput = new Control('');
 
 this.searchInput.valueChanges
 .debounceTime(500)
 .subscribe(stock => this.getStockQuoteFromServer(stock));
 }
 
 getStockQuoteFromServer(stock) {
 
 console.log(`The price of ${stock} is ${100*Math.random().toFixed(4)}`);
 }
 } Observable
  • 51. Http and Observables 
 class AppComponent {
 
 products: Array<string> = [];
 
 constructor(private http: Http) {
 
 this.http.get(‘http://localhost:8080/products')
 .map(res => res.json())
 .subscribe(
 data => {
 
 this.products=data;
 },
 
 err =>
 console.log("Can't get products. Error code: %s, URL: %s ",
 err.status, err.url),
 
 () => console.log('Product(s) are retrieved')
 );
 }
 } DI O b s e r v e r
  • 52. Deployment • We use Webpack bundler for packaging • npm scripts for running the build scripts The app index.html Frameworks
  • 53. Preparing deployment with Webpack • Input: the entry point(s) of your app • Output: transpiled bundle (a .js file) • Resources (css, images, html) can be inlined in the bundle • Usually, the app will have at least two bundles:
 
 - your code (e.g. bundle.js)
 
 - frameworks and libraries (e.g. vendor.bundle.js)
  • 54. Webpack Loaders & Plugins • Loaders operate on a single file (e.g. transpile TS into JS) • Plugins can operate on multiple files and be invoked at different stages of the Webpack lifecycle
  • 55. … module.exports = {
 debug: false,
 devtool: 'source-map',
 entry: {
 'main' : './src/main.ts',
 'vendor': './src/vendor.ts'
 },
 metadata: metadata,
 module: {
 loaders: [
 {test: /.css$/, loader: 'to-string!css'},
 {test: /.html$/, loader: 'raw'},
 {test: /.ts$/, loader: 'ts'}
 ],
 noParse: [path.join(__dirname, 'node_modules', 'angular2', 'bundles')]
 },
 output: {
 path : './dist',
 filename: 'bundle.js'
 },
 plugins: [
 new CommonsChunkPlugin({name: 'vendor', filename: 'vendor.bundle.js', minChunks: Infinity}),
 new CompressionPlugin({regExp: /.css$|.html$|.js$|.map$/, threshold: 1500}),
 new CopyWebpackPlugin([{from: './src/index.html', to: 'index.html'}]),
 new DedupePlugin(),
 new DefinePlugin({'webpack': {'ENV': JSON.stringify(metadata.ENV)}}),
 new OccurenceOrderPlugin(true),
 new UglifyJsPlugin({
 compress : {screw_ie8 : true},
 mangle: {
 screw_ie8 : true,
 except: ['RouterLink'] // TODO: Remove after #6678 fixed
 }
 })
 ],
 resolve: {
 extensions: ['', '.ts', '.js']
 }
 webpack.config.js
  • 56. npm scripts in package.json "scripts": {
 
 "clean": "rimraf dist",
 
 "postinstall": "typings install",
 
 "prebuild": "npm run clean",
 "build": "webpack --config webpack.prod.config.js --progress —profile --display-cached",
 
 "start": "webpack-dev-server --inline --progress --display-cached --port 8080",
 
 "preserve:dist": "npm run build",
 "serve:dist": "static dist -z"
 } To run a script from the command line:
 
 npm start or npm run build or npm run serve:dist
  • 57. Links • A two-day Angular 2 workshop, March 28-29, 2016, New York,
 http://bit.ly/1R0FAhN 
 discount code: jugmember • Angular consulting/training: faratasystems.com • Blog: yakovfain.com • Our book: http://bit.ly/1QYeqL0