Slide 1

Slide 1 text

angular2 @SC Toledo Javier Gamarra / @nhpatt

Slide 2

Slide 2 text

https://youtu.be/WUfxPdwC_PQ (video) https://goo.gl/9MlWoc (slides) https://goo.gl/jwFKcA (repo)

Slide 3

Slide 3 text

who? ● Javier Gamarra / @nhpatt ● @cylicon_valley (07/05|19-21/05) / @agilespain (01-02/06) ● @liferay ● java/javascript

Slide 4

Slide 4 text

environment ● Sublime | Atom | Visual Studio | Visual Studio Code | Webstorm ● Typescript | ES6 | Dart ● npm

Slide 5

Slide 5 text

how? ● Lots of things to explain (2hr code & 2hr talk) ● Commit per commit ● Please ask me, any time ● Or comment in the slides

Slide 6

Slide 6 text

Ask me! Pleeeease

Slide 7

Slide 7 text

background?

Slide 8

Slide 8 text

let’s code!

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

our first app (2/3) Let’s copy app/app.component.ts & app/main.ts

Slide 12

Slide 12 text

our first app (3/3) And lastly, copy the index.html file in the root folder (/)

Slide 13

Slide 13 text

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...

Slide 14

Slide 14 text

interpolation? Let’s change the code of app.component.ts a bit: ● Replace the template for: ‘

{{name}}

’ ● And define a variable inside our Component: export class AppComponent { private name:String = "Hi!" }

Slide 15

Slide 15 text

interpolation? Change the content of the name String and see it reload live… ● thanks lite-server!

Slide 16

Slide 16 text

interpolation? Several things acting in that example: ● Interpolation with {{}} ● private members of a class! ● and with types :)

Slide 17

Slide 17 text

architecture

Slide 18

Slide 18 text

angular2 architecture & concepts

Slide 19

Slide 19 text

concepts ● Components ● Templates ● Metadata ● Data binding ● Modules ● Directive ● Dependency Injection (DI)

Slide 20

Slide 20 text

component ● A class ● Attributes and methods ● Supports a view

Slide 21

Slide 21 text

template ● html code with strange tags ● A hierarchy of components & views

Slide 22

Slide 22 text

metadata ● The glue ● In a decorator (similar to an annotation)

Slide 23

Slide 23 text

databinding ● “A replacement to pushing manually values” ● Interpollation is one way ● Property bindings ● Event bindings ● Two way

Slide 24

Slide 24 text

databinding ● Two way

Slide 25

Slide 25 text

modules ● Optional! ● reusability and separation of concerns ● like namespaces ● System modules (like http)

Slide 26

Slide 26 text

directive ● A system component ● Works with the view

Slide 27

Slide 27 text

services ● A class with business logic

Slide 28

Slide 28 text

dependency injection ● Decouple concepts, instantiation from use ● Needs providers!

Slide 29

Slide 29 text

more concepts and other stuff ● Forms ● HTTP ● Pipes

Slide 30

Slide 30 text

Interpolation & bindings (and TS)

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

objective We want to do sth like this:

Slide 33

Slide 33 text

interfaces 1/2 (TS) Let’s define a contract: interface Option { name: String; description: String; votes: Number; }

Slide 34

Slide 34 text

interfaces 2/2 (TS) Can be implemented implicitly: private option:Option = { name: 'toledo is awesome', description: 'evident', votes: 20 };

Slide 35

Slide 35 text

interfaces Define an interface and render it in the view Hint: {{option.name}}

Slide 36

Slide 36 text

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;...}

Slide 37

Slide 37 text

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) {}

Slide 38

Slide 38 text

complex templates ● Backticks (`) allows us to use multi line strings like: template: `

{{repository.name}}

{{repository.watchers_count}}

`

Slide 39

Slide 39 text

complex templates ● template vs templateUrl ● Path to an .html file which can use the context of the component

Slide 40

Slide 40 text

complex templates and classes ● Test it! ○ Replace your interface with a class ○ Play with the default attributes ○ Or the templateUrl

Slide 41

Slide 41 text

*ngFor ● Let’s use arrays ○ :Array || :Option[] ○ *ngFor=”#option of options” ● #variable -> local variable declarations ● Don’t forget the * -> is creating a tag in the background

Slide 42

Slide 42 text

*ngFor ● Define a list of Options and iterate through their values

Slide 43

Slide 43 text

*ngIf *ngIf=”boolean_condition” removes from the DOM

Slide 44

Slide 44 text

*ngIf ● Hide some attribute depending on a condition

Slide 45

Slide 45 text

types in TS ● boolean | number | string | arrays | enum | Any | Void enum OptionStatus { Abandoned, Active };

Slide 46

Slide 46 text

visibility in typescript ● private/public (everything is public by default)

Slide 47

Slide 47 text

optional properties in TS ● Optional properties (color?: string;)

Slide 48

Slide 48 text

inheritance ● Interfaces can be implemented and extended ● Classes can be extended

Slide 49

Slide 49 text

Angular event bindings: Click me! And in TS: onClickMe($event) { console.log($event); } ● Target & execution context user input

Slide 50

Slide 50 text

user input ● Add a button in each row and log the event

Slide 51

Slide 51 text

user input The source of the event can be anything:

Slide 52

Slide 52 text

user input ● Add a field to include new options in the array ● Test it!

Slide 53

Slide 53 text

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:

Slide 54

Slide 54 text

user input ● Test it!

Slide 55

Slide 55 text

react to events This won’t work (and sth similar did in Angular 1.x):

{{box.value}}

Slide 56

Slide 56 text

react to events ● keyup.enter ● several events ● local template variables and scope

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

Modules

Slide 59

Slide 59 text

modules ● Classes should be on their own package We should export them… And import them That’s it

Slide 60

Slide 60 text

modules ● Test it!

Slide 61

Slide 61 text

one & two-way databinding

Slide 62

Slide 62 text

databindings ● {{}} -> interpolation -> disabled={{component_variable}} ● [] -> property binding -> [disabled]=”component_variable” ● () -> event binding -> (click)=”component_method” ● # -> variable declaration -> ● * -> structural directives ->

Slide 63

Slide 63 text

template expressions ● Interpolation == property binding -> from the component to an element ●

==

{{user.name}}

● disabled={{expression}} == [disabled]=”expression”

Slide 64

Slide 64 text

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.)

Slide 65

Slide 65 text

template expressions Should be: ● Quick ● Simple ● Idempotent

Slide 66

Slide 66 text

attributes vs properties ● Attributes initialize DOM properties and then they are done. ● Property values can change; attribute values can't.

Slide 67

Slide 67 text

attributes vs properties ● use than src={{}} ng-src… & lots of directives in angular 1.x

Slide 68

Slide 68 text

elvis ?. -> elvis operator Null safe operator objeto?.propiedad?.valor

Slide 69

Slide 69 text

elvis Try it!

Slide 70

Slide 70 text

binding types ● Interpolation ● Property ● Attribute * (aria, svg, table span do not have element properties, only [attr.]) ● Class [class.x] ● Style [style.x]

Slide 71

Slide 71 text

let’s use a class/style with a method ● [class.x] ● [style.font-size] =

Slide 72

Slide 72 text

example property databindings ● ● ●
● ●
Special
● [disabled]="isUnchanged"

Slide 73

Slide 73 text

template statements (event)="statement" ● Side effects ● Supports “;” and assignments… ● No new(), ++, +=, console.log or pipes

Slide 74

Slide 74 text

two-way databinding ● ? ● ...

Slide 75

Slide 75 text

two-way databinding ● [()] ○ ● Forms...

Slide 76

Slide 76 text

ok, let’s recap ● Interpolation & property data binding ● Event binding ● Two way data binding Component oriented... but

Slide 77

Slide 77 text

new component ● Component class (+ template) ● Use the selector ● And add it to the directives metadata of the parent class

Slide 78

Slide 78 text

new component ● Test it!

Slide 79

Slide 79 text

inputs @Inputs() variable:type

Slide 80

Slide 80 text

inputs ● Test it!

Slide 81

Slide 81 text

outputs Remember the $event object... EventEmitter: @Output() sth = new EventEmitter();

Slide 82

Slide 82 text

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)

Slide 83

Slide 83 text

outputs ● log in the parent component a child selection...

Slide 84

Slide 84 text

inputs & outputs Inputs/ are not evaluated in constructor ngOnInit -> implement OnInit Several phases (ngOnChanges with map, ngOnDestroy…)

Slide 85

Slide 85 text

Dependency Injection

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

inversion of control Dependency Injection is one way of implementing IoC Basically saying: constructor(@Injectable wheels) {...}

Slide 88

Slide 88 text

inversion of control There are other ways: ● Passing a reference manually ● Factory ● Builder ● ServiceLocator ● ...

Slide 89

Slide 89 text

so what’s dependency injection…? ● A coding pattern ● a class receives its dependencies from external sources rather than creating them itself.

Slide 90

Slide 90 text

and why, again? ● encapsulation ● one reason to change ● flexibility ● testing

Slide 91

Slide 91 text

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()

Slide 92

Slide 92 text

dependency injection in angular ● singletons* ● optional dependencies ● lot’s of config options

Slide 93

Slide 93 text

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

Slide 94

Slide 94 text

http

Slide 95

Slide 95 text

http ● Additional module to do query requests. ● Uses Rx!!!

Slide 96

Slide 96 text

http ● ● <script src="node_modules/rxjs/bundles/Rx.js"> ● import 'rxjs/Rx'; (we add all operators) ● inject HTTP_PROVIDERS ● use http methods and imports

Slide 97

Slide 97 text

http ● text() ● json() ● status headers (object of type Headers) ● retry() ● toPromise()

Slide 98

Slide 98 text

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 => res.json().data) .catch(this.handleError)

Slide 99

Slide 99 text

http ● Don’t return the response object ● Handle errors (do operation)

Slide 100

Slide 100 text

http ● Manual request ● JSONP ● fetch API

Slide 101

Slide 101 text

rx

Slide 102

Slide 102 text

rx Observer

Slide 103

Slide 103 text

rx Observer + Only emit when listening + OnFinished + OnError + Multiple Events + Operators + Combinations + Schedulers (java…)

Slide 104

Slide 104 text

rx ● Creation: Observable.create, just, from ● Operators: take, map, filter, reduce, merge...

Slide 105

Slide 105 text

rx

Slide 106

Slide 106 text

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

Slide 107

Slide 107 text

rx ● Observable.fromEvent(this.el.nativeElement, 'keyup') ● Emitter with Observables

Slide 108

Slide 108 text

rx Observable from button (Subject + click) or: ● [ngFormControl]="element" ● element = new Control() ● element.valueChanges

Slide 109

Slide 109 text

rx 1. WikipediaService 2. Create an Observable of a field 3. Wait 1 second until search 4. Filter repeated results 5. Cancel previous requests

Slide 110

Slide 110 text

rx this.term.valueChanges .debounceTime(400) .distinctUntilChanged() .switchMap(term => this.wikipediaService.search(term));

Slide 111

Slide 111 text

pipes

Slide 112

Slide 112 text

pipes Transform data, typically in interpolation:

The hero's birthday is {{ birthday | date }}

Slide 113

Slide 113 text

pipes ● json pipe ● slice (like python) -> slice:1:2 ● Uppercase & lowercase ● number:’.1-1’ -> integer digits, minfraction, maxfraction ● Percent ● currency ● date with elements only

Slide 114

Slide 114 text

pipes ● Are injectable ● We can roll our own

Slide 115

Slide 115 text

pipes AsyncPipe works with ● Promise ● Observable And renders the result when it’s finished...

Slide 116

Slide 116 text

forms

Slide 117

Slide 117 text

forms ● Controls -> field’s value, states & errors ● Control, ControlGroups & Forms ● Model driven (from JS) vs template driven (ngControl in template)

Slide 118

Slide 118 text

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.

Slide 119

Slide 119 text

controlling the state of the form We can control the full form state: ● (ngSubmit)=”onSubmit()” #variableFormName=”ngForm” ● [disabled]=”!variableFormName.form.valid”

Slide 120

Slide 120 text

controls ● valid ● errors ● dirty ● pristine ● touched ● untouched ● value ● status ● valueChanges

Slide 121

Slide 121 text

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')"

Slide 122

Slide 122 text

validators required minlength maxlength

Slide 123

Slide 123 text

+typescript

Slide 124

Slide 124 text

typescript ● superset ES6 with types & decorators ● Only 1 constructor ● ${variable} in template strings

Slide 125

Slide 125 text

typescript ● let/const (blocks & hoisting) ● String templates ● Arrow functions (implicit return, capture this) ● for of ● Maps & sets

Slide 126

Slide 126 text

typescript ● short syntax for objects ● Rest parameters (...restOfName) & spread ● Destructuring (let { timeout, isCache } = httpOptions) ● Promises & Async/Await

Slide 127

Slide 127 text

typescript ● Accessors ● Type inference ● Function Types & Hybrid Types (interfaces with function types) ● Static properties ● Union types “North” | “East”

Slide 128

Slide 128 text

Final Words

Slide 129

Slide 129 text

so what’s missing? ● Routing ● Model driven forms ● Testing ● Minimization, bundling... ● CLI ● Animations

Slide 130

Slide 130 text

why? ● Opinionated ● Component Oriented ● -> ● ...

Slide 131

Slide 131 text

style guides ● Johnpapa ● imitation

Slide 132

Slide 132 text

angular seeds & bootstraps ● angular2-webpack ● angular2-seed ● official angular2 material ● ng-2 material

Slide 133

Slide 133 text

references ● Becoming a ninja with Angular2 or ng-book2 ● Typescript book or Typescript official guide ● Cheatsheet ● Angular 2 official guide ● Awesome resources & more

Slide 134

Slide 134 text

questions?

Slide 135

Slide 135 text

feedback: https://goo.gl/47U1z6 nhpatt @(gmail | twitter)

Slide 136

Slide 136 text

angular2 @SC Toledo Javier Gamarra / @nhpatt