angular 2 - files.meetup.com 2 - alt.net april 27 2016.pdf · angular 2 integrates jasmine for unit...
Post on 21-May-2020
7 Views
Preview:
TRANSCRIPT
Contact Info
Howard Pinsley
Senior Software Engineer Lab49
Email: hpinsley@gmail.com
Twitter: @hpinsley
Blog: http://howardpinsley.com/wordpress/
Github: http://github.com/hpinsley/angular-mashup
LinkedIn: https://www.linkedin.com/in/hpinsley
My Slides Stink
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
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
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
… 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
Application Building Blocks● Module
● Component
● Template
● Metadata
● Data Binding
● Service
● Directive
● Dependency Injection
How it Fits Together
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
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
Module Imports & Decorators
import {Component} from 'angular2/core';
...
@Component({
selector: 'state-stats',
...
})
export class StateStats {
...
}
MODULE IMPORT
DECORATOR
CLASS BEING DECORATED
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
Recognize this person?
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.
Bootstrapping
● Import from the appropriate modules● Specifying the root component● Specifying the root injector providers
Example: Bootstrap Code Sample
The Component Tree
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
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
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
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
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
“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" >
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
Dependency Injection Configuration
provide(MyService, {useClass: MyMockService})provide(MyService, {useFactory: myFactory})provide(MyValue, {useValue: 41})
● Class
● Factory function
● Value
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 {...
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>
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
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
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.
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
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
What can we steal from the React Community?
Redux
https://egghead.io/series/getting-started-with-redux
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
A Few Resources● https://angular.io/
○ https://angular.io/docs/ts/latest○ https://angular.io/docs/js/latest/resources.html
● http://angularjs.blogspot.com● http://blog.thoughtram.io/categories/angular-2/● https://github.com/angular/angular● https://github.com/mgechev/angular2-seed● http://blog.mgechev.com/● https://github.com/hpinsley/angular-mashup● https://angular-mashup.herokuapp.com● https://github.com/Reactive-Extensions/RxJS● http://rxmarbles.com/
Interesting Plunks and Links
● HTTP Error Handling● https://github.com/AngularShowcase● http://teropa.info/blog/2015/03/02/change-and-its-detection-in-javascript-frameworks.html
Questions?
top related