angular 2 - files.meetup.com 2 - alt.net april 27 2016.pdf · angular 2 integrates jasmine for unit...

40
Angular 2 http://angular.io Alt.Net - April 27, 2016

Upload: others

Post on 21-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Angular 2

http://angular.io

Alt.Net - April 27, 2016

Page 2: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Contact Info

Howard Pinsley

Senior Software Engineer Lab49

Email: [email protected]

Twitter: @hpinsley

Blog: http://howardpinsley.com/wordpress/

Github: http://github.com/hpinsley/angular-mashup

LinkedIn: https://www.linkedin.com/in/hpinsley

Page 4: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

My Slides Stink

Page 5: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

But Angular 2 is• A complete re-write• Component based, hierarchical layout• Embraces ES6/ES7/TypeScript• Integrates Reactive Programming• Simpler API• Built for web and mobile• Built for performance

Page 6: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Design Goals (March 2014)

More Capable

● Modern Evergreen browsers

● ECMAScript6

● Faster change detection

● Instrumented

● Modular● Misc

performance optimizations

● Dependency Injection

● Templating & Directives

● Touch animations

● Router● Persistence

Designed for Future Faster Simpler

See http://angularjs.blogspot.com/2014/03/angular-20.html?view=timeslide

Page 7: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Where are we now: 2.0.0-beta.15 (4/13/2016)

● SPEED & PERFORMANCE● SIMPLE & EXPRESSIVE● CROSS PLATFORM● SEAMLESS UPGRADE FROM ANGULAR 1● FLEXIBLE DEVELOPMENT● COMPREHENSIVE ROUTING● DEPENDENCY INJECTION● LEGACY BROWSER SUPPORT● ANIMATIONS (under development)● INTERNATIONALIZATION (I18N) & ACCESSIBILITY (under development)

See https://angular.io/features.html

Architectural features

Page 8: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

… before angular-cli

● Recommend you start with a seed project

● I recommend https://github.com/mgechev/angular2-seed

○ TypeScript used throughout.○ Gulp build system -- also implemented in TypeScript○ Has been evolving since the early alpha versions of

Angular 2○ Integrates Jasmine for unit tests and Protractor for end-to-end

testing.○ Easy to extend

Page 11: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

How it Fits Together

Page 12: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

ES6/ES2015 - Irresponsibly brief overviewclass Animal {

type:string;

constructor(type:string) {

this.type = type;

}

}

class Shark extends Animal {

name: string;

constructor(name:string) {

super('fish');

this.name = name;

}

bite() {

console.log(`Shark ${this.name} (a ${this.type}) is biting.`);

}

}

CLASS

INTERPOLATED STRING

Page 13: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Arrow Functions

let dogs = [new Dog("fido"), new Dog('lassie')];

let sharks = [new Shark('jaws'), new Shark('killer')];

dogs.forEach(dog => dog.bark());

sharks.forEach(shark => shark.bite());

[...dogs, ...sharks].forEach(animal => console.log(animal.name));

Arrow Function

Spread operator

Page 14: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Module Imports & Decorators

import {Component} from 'angular2/core';

...

@Component({

selector: 'state-stats',

...

})

export class StateStats {

...

}

MODULE IMPORT

DECORATOR

CLASS BEING DECORATED

Page 15: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

TypeScript

"We love TypeScript for many things... With TypeScript, several of our team members have said things like 'I now actually understand most of our own code!' because they can easily traverse it and understand relationships much better. And we’ve found several bugs via TypeScript’s checks.”

Brad Green, Engineering Director - AngularJS

Page 16: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Recognize this person?

Page 17: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

The Man Behind the Curtain

Anders Hejlsberg (/hɑːlsbɛrɡ/, born December 1960)[2] is a prominent Danish software engineer who co-designed several popular and commercially successful programming languages and development tools. He was the original author of Turbo Pascal and the chief architect of Delphi. He currently works for Microsoft as the lead architect of C#[1] and core developer on TypeScript.

Page 18: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Bootstrapping

● Import from the appropriate modules● Specifying the root component● Specifying the root injector providers

Example: Bootstrap Code Sample

Page 19: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

The Component Tree

Page 20: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Components

import {Component} from 'angular2/core';

import {CORE_DIRECTIVES} from 'angular2/common';

import {IStateAccidentStats} from './StateAccidentStats';

@Component({

selector: 'state-stats',

templateUrl: './components/streaming/StateStats.html',

styleUrls: ['./components/streaming/StateStats.css'],

inputs: ['stats'],

directives: [CORE_DIRECTIVES]

})

export class StateStats {

stats:IStateAccidentStats[] = [];

}

DECORATOR

Page 21: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Template<h2>Traffic Info</h2>

<table class="table table-condensed">

<thead>

<tr>

<th>State</th>

<th>Accidents</th>

<th>Vehicles</th>

</tr>

</thead>

<tbody>

<tr *ngFor="#stat of stats">

<td>{{stat.state}}</td>

<td>{{stat.numberOfAccidents}}</td>

<td>{{stat.numberOfVehicles}}</td>

</tr>

</tbody>

</table>

Model Object

Local Variable

Interpolated Expression

Built-in directive

Page 22: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Consuming the Component● Import the component from its module● Add the component to the parent’s Directives array● Use the component by specifying its declared selector● Specify any input properties and bind to expressions on the parent

...

import {StateStats} from './StateStats';

@Component({

selector: 'weather',

templateUrl: './components/streaming/Weather.html',

styleUrls: ['./components/streaming/Weather.css'],

directives: [CORE_DIRECTIVES, StateStats]

})

export class Weather {...

…<div class="col-md-3">

<state-stats [stats]="stateStats"></state-stats>

</div>

COMPONENT

TEMPLATE

Page 23: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Template Syntax - Event Binding

● Can bind to any event● Includes custom events from components● Does away with ng-click, ng-change, etc.● Indicated by parens● Right-hand side evaluated as an expression on the component

<div>

<button (click)="previous()" ...>Back</button>

<button (click)="next()" ...>Next</button>

<button (click)="scoreTest()" ...>Grade</button>

</div>

Example

Page 24: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Template Syntax - Property Binding● Bind to an element’s properties rather than its attributes.● Can assign arbitrary objects; not limited to strings● Does away with ng-src and others.● Indicated by brackets● Right-hand side evaluated as an expression on the component

<div>

<button [hidden]="question.questionNumber === 1">Back</button>

<button [hidden]="question.questionNumber === quiz.questionCount">Next</button>

<button [hidden]="question.questionNumber !== quiz.questionCount">Grade</button>

</div>

Example

Page 25: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

“Two-Way” Data Binding for Form Elements

Angular 2 does not have 2-way data binding per se.

It is implemented by using both the property and event syntax. We could do it with:

<input [value]="name" (input)="name = $event.target.value">

Rather we use a combination of property and event binding

<input [(ngModel)]="name" >

Page 26: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Dependency Injection

● Improves on the brittle DI implementation of Angular 1

● No longer based on strings but rather uses an OpaqueToken

● Providers can be specified using a string, a class type, or an OpaqueToken. Internally, the Provider turns the string and class parameter into an OpaqueToken; the injector locates dependency values and providers by this token

● Multiple injectors arranged in a hierarchy

● bootstrap gives you access to the root injector

Page 27: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Dependency Injection Configuration

provide(MyService, {useClass: MyMockService})provide(MyService, {useFactory: myFactory})provide(MyValue, {useValue: 41})

● Class

● Factory function

● Value

Page 28: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Singletons and the Injector Hierarchy

● In general, each injector supplied consumers with singleton objects

● What if you need separate instances for each instance of a component?

Defining (or re-defining) a provider at the component level creates a new instance of the service for each new instance of that component.

● The @Component decorator can specify a providers array for dependencies to be injected in a specific component instance and its children.

@Component({

selector: 'hero-editor',

providers: [RestoreService],

template: `...`

})

export class HeroEditor {...

Page 29: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

The Component Router

● Takes the best features of the popular ui-router from Angular 1.● Associated routes with Components rather than controller/view pairs● Advanced features such as child and sibling routes

@Component({ ... })@RouteConfig([ {path:'/crisis-center', name: 'CrisisCenter', component: CrisisListComponent}, {path:'/heroes', name: 'Heroes', component: HeroListComponent}, {path:'/hero/:id', name: 'HeroDetail', component: HeroDetailComponent}])export class AppComponent { }

<h1>Component Router</h1><nav>

<a [routerLink]="['CrisisCenter']">Crisis Center</a> <a [routerLink]="['Heroes']">Heroes</a></nav><router-outlet></router-outlet>

Page 30: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Lifecycle HooksDirective and component instances have a lifecycle as Angular creates, updates, and destroys them.

● ngOnChanges - called when an input or output binding value changes

● ngOnInit - after the first ngOnChanges

● ngDoCheck - developer's custom change detection

● ngAfterContentInit - after component content initialized

● ngAfterContentChecked - after every check of component content

● ngAfterViewInit - after component's view(s) are initialized

● ngAfterViewChecked - after every check of a component's view(s)

● ngOnDestroy - just before the directive is destroyed.

Running example

Source

Page 31: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Directives

● Very little difference between a component and a directive

● In fact the Component decorator inherits from the Directive decorator

● There are structural directives (e.g. *ngFor, to modify the DOM’s structure) and attribute directives (to influence behavior)

● Can also be an attribute on a DOM element to affect custom behavior

● No more arcane directive api.

Sample - Bar Chart

Page 32: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Change Detection● Much Faster than Angular 1● Relies on zone.js which runs your code in a “zone” and monkey-

patches the global async functions● Relies on one-way data binding.● Can go perform even faster if you use immutable data in your

components.

Page 33: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Immutability

The main benefit of using immutable data structures is not to gain rendering performance, but to simplify your application architecture.

Basically application state change can be caused by three things:

● Events - click, submit, …

● XHR - Fetching data from a remote server

● Timers - setTimeout(), setInterval()

http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

Page 34: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

How do I Upgrade?

One of the keys to a successful upgrade is to do it incrementally, by running the two frameworks side by side in the same application, and porting Angular 1 components to Angular 2 one by one. This makes it possible to upgrade even large and complex applications without disrupting other business, because the work can be done collaboratively and spread over a period of time. The upgrade module in Angular 2 has been designed to make incremental upgrading seamless.

https://angular.io/docs/ts/latest/guide/upgrade.html

Page 35: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

What can we steal from the React Community?

Page 37: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Building from the Seed in

git clone --depth 1 https://github.com/mgechev/angular2-seed.git

cd angular2-seed (this one doesn’t count!)

npm install

npm start

Others Useful Ones

npm run build.docs

npm run build.dev

npm run build.prod

Commands

Page 40: Angular 2 - files.meetup.com 2 - Alt.Net April 27 2016.pdf · Angular 2 Integrates Jasmine for unit tests and Protractor for end-to-end testing. Easy to extend. Angular Mashup. Application

Questions?