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