Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Angular2 @SC Toledo

Angular2 @SC Toledo

Workshop sobre Angular2 impartido en el meetup de Software Craftsmanship Toledo.

Javier Gamarra

April 23, 2016
Tweet

More Decks by Javier Gamarra

Other Decks in Programming

Transcript

  1. who? • Javier Gamarra / @nhpatt • @cylicon_valley (07/05|19-21/05) /

    @agilespain (01-02/06) • @liferay • java/javascript
  2. environment • Sublime | Atom | Visual Studio | Visual

    Studio Code | Webstorm • Typescript | ES6 | Dart • npm
  3. how? • Lots of things to explain (2hr code &

    2hr talk) • Commit per commit • Please ask me, any time • Or comment in the slides
  4. our first app Our first app in 5 minutes: •

    package.json • tsconfig.json • typings.json • app/app.component.ts • app/main.ts • index.html Or clone https://github.com/nhpatt/angular2- toledo/ And checkout 10bbef28d9e7ad06957c07533736cff5a59c0c6c https://github.com/nhpatt/angular2-toledo/commit/10bbef28d9e 7ad06957c07533736cff5a59c0c6c
  5. our first app (1/3) Let’s copy them, starting with •

    package.json, • tsconfig.json • and typings.json to / folder And then do a npm install
  6. our first app? So let’s launch our app with npm

    start Everything works, right? Let’s see step by step what we have done...
  7. interpolation? Let’s change the code of app.component.ts a bit: •

    Replace the template for: ‘<h1>{{name}}</h1>’ • And define a variable inside our Component: export class AppComponent { private name:String = "Hi!" }
  8. interpolation? Change the content of the name String and see

    it reload live… • thanks lite-server!
  9. interpolation? Several things acting in that example: • Interpolation with

    {{}} • private members of a class! • and with types :)
  10. concepts • Components • Templates • Metadata • Data binding

    • Modules • Directive • Dependency Injection (DI)
  11. databinding • “A replacement to pushing manually values” • Interpollation

    is one way • Property bindings • Event bindings • Two way
  12. modules • Optional! • reusability and separation of concerns •

    like namespaces • System modules (like http)
  13. example app: voting! Let’s change our app to list something

    more useful… a voting app (like reddit) We will show several options And users will be able to upvote or downvote them
  14. interfaces 1/2 (TS) Let’s define a contract: interface Option {

    name: String; description: String; votes: Number; }
  15. interfaces 2/2 (TS) Can be implemented implicitly: private option:Option =

    { name: 'toledo is awesome', description: 'evident', votes: 20 };
  16. classes (TS) Let’s swap our interface for a class And

    it works… But classes are more similar as other languages… constructor(name, desc, votes) {this.name = name;...}
  17. classes (TS) We have default parameters (no more ||): constructor(name,

    desc, votes = 0) {} And we have brief constructors :) constructor(public name = ‘Toledo’, public votes = 0) {}
  18. complex templates • Backticks (`) allows us to use multi

    line strings like: template: `<h1>{{repository.name}}</h1> <p> <h2>{{repository.watchers_count}}</h2>`
  19. complex templates • template vs templateUrl • Path to an

    .html file which can use the context of the component
  20. complex templates and classes • Test it! ◦ Replace your

    interface with a class ◦ Play with the default attributes ◦ Or the templateUrl
  21. *ngFor • Let’s use arrays ◦ :Array<Option> || :Option[] ◦

    *ngFor=”#option of options” • #variable -> local variable declarations • Don’t forget the * -> is creating a tag in the background
  22. types in TS • boolean | number | string |

    arrays | enum | Any | Void enum OptionStatus { Abandoned, Active };
  23. user input The source of the event can be anything:

    <input (keyup)="onKey($event)">
  24. user input We can improve that code in several ways:

    • We could type the event • Or we could pass the value (way better!) With a local template identifier: <input #name (keyup)="onKey(name.value)">
  25. react to events This won’t work (and sth similar did

    in Angular 1.x): <input #box> <p>{{box.value}}</p>
  26. ok, let’s recap • We have a component • Using

    Typescript • Rendering a list with *ngFor and *ngIf • And displaying values stored in JS • And reacting to events
  27. modules • Classes should be on their own package We

    should export them… And import them That’s it
  28. databindings • {{}} -> interpolation -> disabled={{component_variable}} • [] ->

    property binding -> [disabled]=”component_variable” • () -> event binding -> (click)=”component_method” • # -> variable declaration -> <input #name> • * -> structural directives -> <p *ngFor=”#repo of repositories”>
  29. template expressions • Interpolation == property binding -> from the

    component to an element • <p [textContent]="user.name"></p> == <p>{{user.name}}</p> • disabled={{expression}} == [disabled]=”expression”
  30. template expressions • template expressions are like JS -> textContent={{1

    + 1 + getVal()}} • the template expressions are evaluated and then converted to string • Visible side effects are not allowed (assignments, new(), ‘;’, ++) • Global namespace is not allowed (Math, window.)
  31. attributes vs properties • Attributes initialize DOM properties and then

    they are done. • Property values can change; attribute values can't.
  32. attributes vs properties • use <img [src] /> than src={{}}

    ng-src… & lots of directives in angular 1.x
  33. binding types • Interpolation • Property • Attribute * (aria,

    svg, table span do not have element properties, only [attr.]) • Class [class.x] • Style [style.x]
  34. example property databindings • <img [src] = "url"> • <app

    [repo]="repo"></app> • <div [ngClass] = "{selected: isSelected}"></div> • <button [style.color] = "isSpecial ? 'red' : 'green'"> • <div [class.special]="isSpecial">Special</div> • [disabled]="isUnchanged"
  35. template statements (event)="statement" • Side effects • Supports “;” and

    assignments… • No new(), ++, +=, console.log or pipes
  36. ok, let’s recap • Interpolation & property data binding •

    Event binding • Two way data binding Component oriented... but
  37. new component • Component class (+ template) • Use the

    selector • And add it to the directives metadata of the parent class
  38. outputs • declare the output (@Output()) and create an EventEmitter

    (sth:EventEmitter<> = new EventEmitter<>()) • emit an event (sth.emit(object)) • And listen in the parent component (sth)=method(object)
  39. inputs & outputs Inputs/ are not evaluated in constructor ngOnInit

    -> implement OnInit Several phases (ngOnChanges with map, ngOnDestroy…)
  40. inversion of control Inversion of control is the key When

    we write new something() we add some coupling That something can’t be a child class because of new
  41. inversion of control Dependency Injection is one way of implementing

    IoC Basically saying: constructor(@Injectable wheels) {...}
  42. inversion of control There are other ways: • Passing a

    reference manually • Factory • Builder • ServiceLocator • ...
  43. so what’s dependency injection…? • A coding pattern • a

    class receives its dependencies from external sources rather than creating them itself.
  44. simplest example • Let’s create a “real” service class •

    Pass it in as an argument in providers metadata • And inject it in the constructor and imports. and maybe @Injectable()
  45. dependency injection in angular • provide(RaceService, {useClass: RaceService} ◦ with

    the dependencies • useExisting • useValue • useFactory: () => IS_PROD ? new RaceService() : new FakeRaceService() • DI tokens • multi: true • add to default injectors
  46. http • text() • json() • status headers (object of

    type Headers) • retry() • toPromise()
  47. http let body = JSON.stringify({ name }); let headers =

    new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.url, body, options) .map(res => <Entity> res.json().data) .catch(this.handleError)
  48. rx

  49. rx Observer + Only emit when listening + OnFinished +

    OnError + Multiple Events + Operators + Combinations + Schedulers (java…)
  50. rx

  51. rx Observable.fromEvent($input, 'keyup') .map(function (e) { return e.target.value; // Project

    the text from the input }) .filter(function (text) { return text.length > 2; // Only if the text is longer than 2 characters }) .debounce(750 /* Pause for 750ms */ ) .distinctUntilChanged(); // Only if the value has changed
  52. rx Observable from button (Subject + click) or: • [ngFormControl]="element"

    • element = new Control() • element.valueChanges
  53. rx 1. WikipediaService 2. Create an Observable of a field

    3. Wait 1 second until search 4. Filter repeated results 5. Cancel previous requests
  54. pipes • json pipe • slice (like python) -> slice:1:2

    • Uppercase & lowercase • number:’.1-1’ -> integer digits, minfraction, maxfraction • Percent • currency • date with elements only
  55. forms • Controls -> field’s value, states & errors •

    Control, ControlGroups & Forms • Model driven (from JS) vs template driven (ngControl in template)
  56. forms • ngControl tracks the state and changes the css

    classes • We can (follow me on this), assign ngControl to a field, and assign a local variable from this form.
  57. controlling the state of the form We can control the

    full form state: • (ngSubmit)=”onSubmit()” #variableFormName=”ngForm” • [disabled]=”!variableFormName.form.valid”
  58. controls • valid • errors • dirty • pristine •

    touched • untouched • value • status • valueChanges
  59. template driven • we don’t want to submit in onclick

    (ngSubmit)=”action()” • we need a form alias to check #userForm="ngForm" • ngModel • we need ngControl="password" • #password="ngForm" • *ngIf="password.control?.dirty && password.control?.hasError('required')"
  60. typescript • superset ES6 with types & decorators • Only

    1 constructor • ${variable} in template strings
  61. typescript • let/const (blocks & hoisting) • String templates •

    Arrow functions (implicit return, capture this) • for of • Maps & sets
  62. typescript • short syntax for objects • Rest parameters (...restOfName)

    & spread • Destructuring (let { timeout, isCache } = httpOptions) • Promises & Async/Await
  63. typescript • Accessors • Type inference • Function Types &

    Hybrid Types (interfaces with function types) • Static properties • Union types “North” | “East”
  64. so what’s missing? • Routing • Model driven forms •

    Testing • Minimization, bundling... • CLI • Animations
  65. references • Becoming a ninja with Angular2 or ng-book2 •

    Typescript book or Typescript official guide • Cheatsheet • Angular 2 official guide • Awesome resources & more