Angular js 2

47
AngularJs 2.0 Building SPA With AngularJs 2.0 Ran Wahle

Transcript of Angular js 2

Page 1: Angular js 2

AngularJs 2.0 Building SPA With AngularJs 2.0Ran Wahle

Page 2: Angular js 2

Agenda

• AngularJs History

• Getting started with AngularJs 2.0

• AngularJs modules and components

• User input and data binding

• Directives

• Injectable services

• Pipes

• Routing

• Migrating from angular 1

Page 3: Angular js 2

Some FAQs before we begin

• Do I need to know angular 1.x ?No (It helps with the migration part)

• Do I need to know typescript ?It helps but no

• Do I need to know ES2015 ?It helps but no

• Do I need to know javascript ?Yes

Page 4: Angular js 2

AngularJs history facts

• First developed in 2009

• Previously named “Locality-filteration”

• Founded my Mishko Havery and Igor Minar

• Created to replace GWT

Page 5: Angular js 2

AngularJs timeline

First iteration (2009)

Angular 2.0 announced (2014)

Angular 2.0 beta (Dec 2015)

Page 6: Angular js 2

Angular 1 & 2

Angular 1.x

• Built on ES5 standards

• jQLite based

• Opinionated

• Performances issue

Angular 2

• Built on ES2015 and above standards

• Supports new HTML5 standards

• Less opinionated

• Better performances

Page 7: Angular js 2

Getting started

• Install node

• Get angular dependencies and dev dependencies

• Reference polyfill and angular libraries in your main HTML

• Configure AMD

Page 8: Angular js 2

Dependencies

• ES6 shim – Polyfills for es2015

• System.JS – AMD library

• IE polyfills

• RX.js – Javascript reactive extension

Page 9: Angular js 2

Configuring system.js

• System.config({ packages: { app: { format: 'register', //the format for es6 modules defaultExtension: 'js‘ //javascript fiels extension } }});System.import('app/main') //Import our main entry .then(null, console.error.bind(console));

Page 10: Angular js 2

Our main entry file

• //import bootstrap and our app main componentimport {bootstrap} from 'angular2/platform/browser';import {AppComponent} from './components/app.component';

//bootstrap our app componentbootstrap(AppComponent);

Page 11: Angular js 2

Our main component

import {Component} from 'angular2/core';@Component({ selector: 'my-app', template: `<h1>Color guessing game 2</h1> <guessing-grid>Loading...</guessing-grid>`, directives: [GuessingGrid]

})export class AppComponent {

}

Decorator

HTML template

Selector

“Controller”

Other components

Page 12: Angular js 2

Components and modules

• Angular 2.0 building blocks are components

• Components can be consist of both HTML elements logic.

• Using the components is enable via HTML tags defined in the component selector

Angular1.x – Components exist from v1.5 however we could equivalent it to directive for 1.4 and below

Page 13: Angular js 2

Using your components

• You may consume your component in another component 1. Put the component’s tag in the other components HTML 2. Import the component class in your component’s code 3. Put the component class in the directives array

• You may consume your component directly from HTML1. Put the component’s tag in HTML2. Boostrap your component

In angular 1.x you need to make sure that the javascript is loaded as well

Page 14: Angular js 2

Data binding

• Attributes binding

• Events binding

• Two way binding

• Local variables

In Angular 1.x we had a directive for every attribute or event we wanted to bind data to

Page 15: Angular js 2

Binding types

• <element [attribute]=“boundedData” ></element>

• <element (event)=“expression”></element>

• <element>{{expression}}</element>

Page 16: Angular js 2

Components hierarchy

• Components can use other components

• Components can bind data into other components

• Components can subscribe to their child componets events

Page 17: Angular js 2

Component input / output

• Using component input, you can bind data into it

@Component({…inputs: [‘input1’, ‘input2’, … ]…}

<component-selector [input1]=“expr1” [input2]=“expr2”></component-selector>

Page 18: Angular js 2

Component input / output

• Using component output, you expose events from it

@Output()outputprop = new EventEmitter()

//invokethis.outputprop.emit(args)

<component-selector (outputprop)=“expr1” [input2]=“expr2”></component-selector

Page 19: Angular js 2

Directives

• Writing an attribute directive

• Built in attribute directives

Page 20: Angular js 2

Attribute directive

• Use @Directive decorator

• The selector should have square brackets (i.e. [attribute] )

• As in component, you should export a class

• The class constructor gets an ElementRef as the parameterpointing to the directive’s element.

• You may manipulate the element by it’s nativeElement member

Page 21: Angular js 2

Attribute directive

import {Directive, ElementRef, Input} from 'angular2/core';

@Directive({

selector: '[myAttributeTirective]'

})

export class AttributeDirective {

constructor(el: ElementRef) {

el.nativeElement.style.backgroundColor = 'yellow';

}

}

Page 22: Angular js 2

Consuming your directive

• Import your directive class

• Put your class in the component’s directives array

• Put your directive’s selector inside your component’s template

Page 23: Angular js 2

Consuming your directive

import {Component} from 'angular2/core';

import {AttributeDirective} from './attributeDirective';

@Component({

selector: 'my-app',

template ‘<element my-attribute-directive=“”></element>`

directives: [AttributeDirective]

})

export class MyComponent { }

Page 24: Angular js 2

Built in directives

• *ngFor

• *ngIf

• [ngSwitch]

• [ngModel]

Page 25: Angular js 2

Injectable services

• Services are building blocks that has logic only without UI

• We use them for separation between UI and logics

• To have our code as injectable service we put @Injectable decorator on top of our class.@Injectable export class OurService {}

• To use it, we inject it in our consuming class constructor.constructor(private _service: OurService) { }

• You also need to register the injectable service in your providers array

Page 26: Angular js 2

HttpClient

• Instance members overview

• About the Observable<Response>

• Fetch API

Page 27: Angular js 2

HttpClient

• Include http.dev.js pollyfil

• Include rx.js

• Http can work with both Promise and observable

Page 28: Angular js 2

HttpClient promise base

• http.get(url, data).toPromise().catch(… )

.then(…)

In Angular 1.x we didn’t have to JSON.stringify, we do in angular 2

Page 29: Angular js 2

Observable based

• You subscribe on the actual data

• You map the response data to the data other subscribe to

• Other soubscribe to the object that “map” retunrs

• http.get(url).map(res => <type> res.json().data).subscribe(data => this.gamerName = data);

Page 30: Angular js 2

Pipes

• What is pipe ?

• Writing pipes

• Some built in pipes

Page 31: Angular js 2

What is pipe

• Pipes the data from the component into the screen

• Manipulate the data while piping it

• Previously known as “filter”

Page 32: Angular js 2

Writing a pipe

• Import Pipe and PipeTransfonrm

• Use @Pipe decorator

• In your class, implement PipeTransform

• Write a method named transform

Page 33: Angular js 2

Writing a pipe

• import {PipeTransform, Pipe} from "angular2/core";@Pipe({name: 'hitMiss'})

export class HitMissPipe implements PipeTransform{ transform(value: string) : string{ return value + '|'; }}

Page 34: Angular js 2

Consuming a pipe

• Import the pipe class

• Register the pipe in your component’s pipes array

• Whenever you bind data and wishes to use the pipe write “data | pipeName”

Page 35: Angular js 2

Consuming a pipe

• import {HitMissPipe} from "../pipes/HitMissPipe"@Component({ selector: 'guess-details',

template: `… <div *ngFor="#result of guess.result" [textContent]="result | hitMiss " style="float:left;"></div> </div>`, … pipes: [HitMissPipe]})

export class MyComponentClass{

}

Page 36: Angular js 2

Routing and navigation

• Using the # sign in SPA

• Angular 2.0 component router

Page 37: Angular js 2

Component Router configuration

• On your app component, use a @RouterConfig decorator

• This decorator receives an array of routing objects

• Each routing object contains:path : URL for routing (unique)name: Route name (unique)component: Component class

Page 38: Angular js 2

Add the router

• Manually (as for beta 13) include the routing library

• Use “base href”

• Import RouteConfig

• Add ROUTER_PROVIDERS to the app proviers

• Configure the router

Page 39: Angular js 2

RouterConfig

@RouteConfig([

{

path: '/path/to/',

name: UniqueRouteName',

component: YourComponentClassName

}

])Angular1.x – Component based routes exist since 1.4 with ng-new-router

Page 40: Angular js 2

Routing

• Make sure you import all components

• Make sure you put <baes href=“/” /> inside your head section

Page 41: Angular js 2

Migration

• Prepare

• Use the upgrade adapter

Page 42: Angular js 2

Prepare - Componentize your app

• Put each component / directive / filter / service in a different module

• Have the app module depend on the above modules (instead of registering the above on the app module)

Page 43: Angular js 2

Prepare - Migrate to typescript

• Typescript is a superset of javascript

• You may simply change file extension to .ts and your app will stay the same.

• Use module loader for javascript files loading (SystemJs, WebPack, Broserify)

• Typescript will use your preferred module loader on your import / export

Page 44: Angular js 2

Upgrade using the UpgradeAdapter

• Bootstrap your angular 1 app instead of using ng-app

• Bootstrap your angular2 app with UpgradeAdapter.bootstrap

• Now you have angular 1+2 hybrid app.

Page 45: Angular js 2

Summary

• Angular 2.0 is a component based framework for SPA

• It uses new standards and therefore a complete rewrite of angular 1.x

• It is much simpler to learn

Page 46: Angular js 2

Additional resources

• Angular site: http://angular.io

• Angular JS official blog:https://blog.angularjs.org/

• ChangeLog:https://github.com/angular/angular/blob/master/CHANGELOG.md

Page 47: Angular js 2

Thank [email protected]@ranwahlehttp://blogs.Microsoft.co.il/ranw