AngularJs 2.0 Building SPA With AngularJs 2.0Ran Wahle
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
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
AngularJs history facts
• First developed in 2009
• Previously named “Locality-filteration”
• Founded my Mishko Havery and Igor Minar
• Created to replace GWT
AngularJs timeline
First iteration (2009)
Angular 2.0 announced (2014)
Angular 2.0 beta (Dec 2015)
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
Getting started
• Install node
• Get angular dependencies and dev dependencies
• Reference polyfill and angular libraries in your main HTML
• Configure AMD
Dependencies
• ES6 shim – Polyfills for es2015
• System.JS – AMD library
• IE polyfills
• RX.js – Javascript reactive extension
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));
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);
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
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
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
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
Binding types
• <element [attribute]=“boundedData” ></element>
• <element (event)=“expression”></element>
• <element>{{expression}}</element>
Components hierarchy
• Components can use other components
• Components can bind data into other components
• Components can subscribe to their child componets events
Component input / output
• Using component input, you can bind data into it
@Component({…inputs: [‘input1’, ‘input2’, … ]…}
<component-selector [input1]=“expr1” [input2]=“expr2”></component-selector>
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
Directives
• Writing an attribute directive
• Built in attribute directives
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
Attribute directive
import {Directive, ElementRef, Input} from 'angular2/core';
@Directive({
selector: '[myAttributeTirective]'
})
export class AttributeDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
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
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 { }
Built in directives
• *ngFor
• *ngIf
• [ngSwitch]
• [ngModel]
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
HttpClient
• Instance members overview
• About the Observable<Response>
• Fetch API
HttpClient
• Include http.dev.js pollyfil
• Include rx.js
• Http can work with both Promise and observable
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
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);
Pipes
• What is pipe ?
• Writing pipes
• Some built in pipes
What is pipe
• Pipes the data from the component into the screen
• Manipulate the data while piping it
• Previously known as “filter”
Writing a pipe
• Import Pipe and PipeTransfonrm
• Use @Pipe decorator
• In your class, implement PipeTransform
• Write a method named transform
Writing a pipe
• import {PipeTransform, Pipe} from "angular2/core";@Pipe({name: 'hitMiss'})
export class HitMissPipe implements PipeTransform{ transform(value: string) : string{ return value + '|'; }}
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”
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{
}
Routing and navigation
• Using the # sign in SPA
• Angular 2.0 component router
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
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
RouterConfig
@RouteConfig([
{
path: '/path/to/',
name: UniqueRouteName',
component: YourComponentClassName
}
])Angular1.x – Component based routes exist since 1.4 with ng-new-router
Routing
• Make sure you import all components
• Make sure you put <baes href=“/” /> inside your head section
•
Migration
• Prepare
• Use the upgrade adapter
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)
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
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.
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
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
Thank [email protected]@ranwahlehttp://blogs.Microsoft.co.il/ranw
Top Related