1. Angular 2 for Beginners
Oswald Campesato
Consultant/Training:
www.iquarkt.com
ocampesato@yahoo.com
2. What is Angular 2?
• Open source framework for Web apps (from Google)
• component-based architecture
• Knowledge of Angular 1.x is not required
• Web/Mobile/ServerSide
• Production status (09/14/2016)
• Github: https://github.com/angular.io
3. Features of Angular 2
• One-way data binding (by default)
• Two-way data binding (optional)
• Dependency injection (in constructors)
• Support for ES5/ES6/TypeScript
• Angular 2 can be 5x faster than Angular 1.x
• Performance comparable to React(?)
4. Features of Angular 2
• Support for Forms/Routes/Pipes (aka filters)
• Support for HTTP requests
• Support for FRP (Functional Reactive Programming)
• Support for Observables/Promises
• Recommendation: learn TypeScript
5. What is TypeScript?
• Developed by Microsoft (October/2012)
• A superset of ES6 (ECMA2015)
• Optional yet powerful type system + inferencing
• Support for interfaces and classes
• TypeScript 2.0 is available
• NB: Angular 2 is written in TypeScript
6. What is TypeScript?
• A compiled language (tsc compiler)
• Type checking during compile time
• "minimal" extra compile time overhead
• ".ts" files are transpiled into ".js" files (via tsc)
• "lib.d.ts" contains TypeScript definitions
7. What are Transpilers?
• They convert code from one language to another
• Babel (formerly 6to5):
+converts ES6 (some ES7) to ECMA5
+ appears to be the de facto standard
• Traceur (Google):
+ converts ES6 to ECMA5
+ used by Angular 2
TypeScript (MicroSoft): http://www.TypeScriptlang.org
8. TypeScript Improvements over ES5
• Types (including Generics)
• Classes, interfaces, and inheritance
• Annotations
• Imports
• language utilities (e.g. destructuring)
9. TypeScript Variables
• var isDone: boolean = false;
• var height: number = 6;
• var name: string = "dave";
• var myList:number[] = [1, 2, 3]; // option #1
• var myList:Array<number> = [1, 2, 3]; // option #2
• var changeMe: any = 4;
• changeMe = "I’m a string now";
• var myList:any[] = [3, true, "pizza"];
10. TypeScript Functions
• void return type:
function myLogger(msg?:string): void {
console.log("My custom logger: “+msg);
}
• Generics:
function identity<T>(arg: T): T {
return arg;
}
// output has 'string' type (explicit/inferred):
var output = identity<string>("Dave");
var output = identity("Dave");
11. TypeScript "any" Type
• any return type:
• function selectSomething(x): any {
• if (typeof x == "object") {
• return 10;
• } else {
• return "abc";
• }
• }
NB: "any" type disables type checking
NB: you can disallow implicit "any" in Visual Studio
12. Functions vs Lambda Expressions
• JavaScript Function:
var doubleJS = function(x) { return 2*x; }
• TypeScript Function:
var doubleTS = function(x:number) {return 2*x;}
• Lambda versions of the TypeScript function:
var lambdaTS = (x:number) => 2*x;
var lambdaTS = x => 2*x;
Another Lambda function:
var x = function(delay:number, () =>void) {
// timer code
});
13. TypeScript Interfaces
interface User {
name: string;
weight?: number; // optional
}
function displayUser(user: User) {
console.log(user.name);
}
• This works even without "weight" in the interface:
var aUser = {name: "John Smith", weight:200};
displayUser(aUser);
14. TypeScript Class (part 1)
class User {
fname: string;
lname: string;
constructor(fname:string, lname:string) {
this.fname = fname;
this.lname = lname;
}
fullname():string {
return this.fname+" "+this.lname;
}
}
15. TypeScript Class (part 2)
• var u1:User, u2:User;
• u1 = new User("Jane", "Smith");
• u2 = new User("John", "Jones");
• console.log("user1 = "+u1.fullname());
• console.log("user2 = "+u2.fullname());
NB: use interfaces as arguments of public methods (when
possible) instead of standard JS/TS types or class types
16. TypeScript Constructor
• only one constructor per TS class is permitted
• the same restriction is true for ES6 classes
• TS and ES6 classes can implement multiple interfaces
• NOTE: This is legal code in Java (3 constructors):
public class User {
public User() {}
public User(String fname) { …}
public User(String fname, String lname) { ... }
}
17. Other Stuff about TypeScript
• TypeScript supports JSX (from ReactJS)
• tsc:w detects changes in .ts files
• Webpack with NG2 to detect changes in .tsx files
• NG2 apps support HMR (Hot Module Reloading)
• NB: modifications to .ts files can be handled separately from
.tsx files (and vice versa)
18. Angular 2 and TypeScript
• TypeScript classes (transpiled to ECMA5)
• @ symbol for annotations/decorators
• @Component ({selector, template, … })
• “Typical” class is AppComponent (in app.component.ts)
• Module definition is in app.module.ts
• Bootstrap ‘root’ component from main.ts
19. Creating Angular 2 Apps (1)
A) Use the Angular CLI (WIP) to generate:
Application files/scaffolding/test-related files
Install angular-cli:
[sudo] npm install -g angular-cli@1.0.0-beta.11-webpack.8
Create an NG2 app:
+ ng new myapp
NOTE: current version of angular-cli might not work for large
projects with multiple modules.
22. Creating Angular 2 Apps (2)
B) Use a “starter kit” that contains:
package.json (for npm)
tsconfig.json (for tsc)
index.html
app/main.ts
app/app.module.ts
app/app.component.ts
Then run this command: npm install
25. Angular 2 Support Libraries
• 1) ES6 Shim:
• shims for older JavaScript engines
• for ECMAScript 6 emulation
• 2) Angular 2 Polyfills:
• code for zones, promises, and reflection
• 3) SystemJS:
• a module loader
•
• 4) RxJS:
• a library for reactive programming in JS
• supports Observables: emit streams of data
• Angular uses Observables for asynch code (HTTP requests)
26. Angular 2 App: main.ts
import { platformBrowserDynamic }
from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
NB: options for mobile and server-side are available
28. Angular 2 Example: app.component.ts
import {Component} from ’@angular/core';
@Component({
selector: 'my-app', // located in index.html
template: `<div>Hello from Angular 2</div>`
})
export class AppComponent {}
29. What is Functional Reactive Programming (FRP)?
• 1) Functional programming:
• is more declarative
• often has more abstraction
• can involve higher order functions
• 2) Reactive Programming was introduced in 1997:
“programming with asynchronous data streams”
• Multiple toolkits/libraries available
• event-driven instead of proactive
• Supported languages JS, Java, Scala, Android, Swift, Go, ....
NB: Elm is an FRP language: http://elm-lang.org/
30. What is Functional Reactive Programming (FRP)?
A) Functional Reactive Programming:
• a programming paradigm that was created by Conal Elliott
• his definition has very specific semantics:
• https://stackoverflow.com/questions/1028250/what-is-
functional-reactive-programming
B) looser definition of FRP: a combination of 2 other concepts:
• Reactive Programming: focuses on asynchronous data streams,
which you can listen to and react accordingly
• Functional Programming: emphasizes calculations via
mathematical-style functions, immutability and expressiveness,
and minimizes the use of variables and state
31. ReactiveX on Github
• Rx for 15 languages: https://github.com/ReactiveX
• Rx works in Scala REPL (what about RxSwift?)
• RxJava: ~15,000 stars
• RxAndroid: ~7,500 stars (undergoing revision)
• RxSwift: ~5,000 stars
• RxJS: ~2,500 stars
• RxScala: ~500 stars
32. Popular JavaScript Toolkits for FRP
• RxJS: https://github.com/Reactive-Extensions/RxJS
• Bacon.js: https://baconjs.github.io/
• Kefir.js: https://rpominov.github.io/kefir/
• most.js: https://github.com/cujojs/most
33. Observables: async Event Management
Observable: represents the idea of an invokable collection of
future values or events
Observer: is a collection of callbacks that knows how to listen
to values delivered by the Observable
Subscription: represents the execution of an Observable, is
primarily useful for cancelling the execution
Combines Angular 2 CLI, RxJS, and WebPack:
http://houssein.me/angular2-hacker-news
34. Observables: async Event Management
Operators: are pure functions that enable a functional
programming style of dealing with collections with operations
like map, filter, concat, flatMap, etc
Subject: is the equivalent to an EventEmitter, and the only
way of multicasting a value or event to multiple Observers
Schedulers: are centralized dispatchers to control
concurrency, allowing us to coordinate when computation
happens on e.g. setTimeout or requestAnimationFrame or
others
35. Promises versus RxJS
• "Promises are good for solving asynchronous
operations such as querying a service with an
XMLHttpRequest, where the expected behavior is
one value and then completion.”
• "RxJS unifies both the world of Promises, callbacks
as well as evented data such as DOM Input, Web
Workers, Web Sockets.”
• => use Promises when a future result is guaranteed
and returns a single value
36. Operators in Observables
+ Operators are methods in Observables
+ Operators allow you to compose new observables
+ Create custom operators based on RxJS operators:
Rx.Observable.prototype.myGreatOperator = ....
General syntax of Observable operators:
let obs = Rx.Observable
.firstOperator()
.secondOperator()
.evenMoreOperatorsIfYouWant()
.subscribe(....); // NOW something happens=
Result:
obs is an Observable “connected” to a source
37. Using Observable, ‘range’, and ‘filter’ in RxJS
• var source = Rx.Observable
• .range(0, 20)
• .filter(x => x < 4)
• //output=?
• var source = Rx.Observable
• .range(0, 20)
• .filter(x => x < 4)
• .subscribe(x => console.log("x = "+x))
• //output=?
• Back to Angular 2 …
38. Add Data (app/app.component.ts)
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `<div>{{ city }}</div>`
})
export class AppComponent {
city:string;
constructor() {
this.city = 'New York';
}
}
39. List of Users (app.component.ts)
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `<div><ul>
<li *ngFor='let user of users'> {{ user }} </li>
</ul></div>`
})
export class AppComponent {
users:string[]; // or users:Array<string>;
constructor() {
this.users = ['Jane', 'Dave', 'Tom'];
}
}
40. Angular 2: Handling Events
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<button (click)="clickedMe(event)">Press Me</button>
`
})
export class AppComponent {
clickedMe(event) {
// do stuff here
console.log("you clicked me");
event.preventDefault();
}
}
41. Angular 2: Other Topics
• Angular 2 Routing
• Angular 2 Forms
• Angular 2 and Enterprise App Development:
http://blog.rangle.io/angular-2-0-the-future-of-enterprise-
application-development/
• Angular 2 Testing:
https://devblog.dymel.pl/2016/09/19/testing-in-angular2
42. What about ES6?
• Arrow functions and 'let' keyword
• Block scopes
• Classes and inheritance
• Default parameters
• Destructured assignment
• Generators, Iterators, Maps, and Sets
• Promises and Rest parameters
• Spread operator
• Template Literals
NB: These features are often used in Angular 2 apps
43. ES6 "let" and Arrow Syntax
• let square = x => x * x;
• let add = (x, y) => x + y;
• let pi = () => 3.1415;
• console.log(square(8)); // 64
• console.log(add(5, 9)); // 14
• console.log(pi()); // 3.1415
44. ES6 Class Definition (part 1)
class Rectangle {
constructor(height, width) { // note: no data types
this.height = height;
this.width = width;
}
calcArea() {
return this.height * this.width;
}
}
• var r1 = new Rectangle(5,10);
• var r2 = new Rectangle(25,15);
45. ES6 Class Definition (part 2)
• console.log("r1 area = "+r1.calcArea());
• console.log("r2 area = "+r2.calcArea());
• Test this code here: http://babeljs.io/repl/
• More Examples of ES6 classes:
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Classes
“Things you can do in ES6 but not in ECMA5”:
https://www.youtube.com/watch?v=GbVAMgU3Jj0
46. Browser Status for ES6
• Modern IE: https://goo.gl/56n7IL
• Mozilla: https://goo.gl/iSNDf9
• Chrome: https://www.chromestatus.com/features#ES6
48. What Should I Learn???
• Main features of ES6 and TypeScript 2.0
• "basic" Angular 2.0 and best practices
• Select an IDE:
WebStorm 10: free 30-day trial ($49/year)
Visual Studio Code (free)
Atom (free) with atom-TypeScript extension
• Command Line Tools:
npm, webpack, browserify (older), broccoli
https://github.com/addyosmani/es6-tools
49. Other Technologies to Learn
• Sass/Bootstrap 4 (previous: less)
• HandleBars/Nunjucks (previous: Jade/EJS)
• Material Design (and MDL)
• Firebase/AngularFire
• D3.js for Data Visualization
• Ionic (=Angular for Mobile) & NativeScript
50. Angular 2 + NativeScript
• NativeScript (Telerik) is similar to JavaScript
• “competitor” to React Native(?)
• creates cross-platform native mobile apps
• Install NativeScript:
[sudo] npm install -g nativescript
52. Angular 2 + React Native
Graphics: TypeScript with Angular 2 in a React Native app:
53. Angular 2 and Ionic 2
• toolkit for hybrid cross-platform mobile apps
• Install Ionic 2:
[sudo] npm install -g cordova ionic@beta
• Create an Ionic 2 app:
[sudo] ionic start Ionic2FirstApp blank --v2
• Ionic Native:
http://ionicframework.com/docs/v2/native
54. Angular 2 + Flux
• Flux is a design pattern (Facebook)
• unidirectional data flow
• Many Flux implementations available (at least 17):
flummox, fluxxor, marty, mcfly, …
• Comparison of Flux implementations:
https://github.com/voronianski/flux-comparison
• Angular 2 works with Flux implementations
55. Angular 2 + Redux
• Redux: the most popular Flux implementation
• Application data is stored outside of applications
• Key parts: Actions, Dispatcher, reducer, and Store(s)
• Alt and Mobx: simpler alternatives to Redux
• Angular 2 works with Redux
56. Angular 2 + GraphQL
• GraphQL: a server-side schema for application data
• Can “wrap” NoSQL and relational stores
• GraphQL server processes requests and returns data
• GraphiQL: https://github.com/skevy/graphiql-app
• GraphQL does not need Relay (but Relay needs GraphQL)
• Angular 2 works with GraphQL
57. GraphQL: What is it?
• a schema for graph-oriented data (Facebook/2012)
• well-suited for micro-service style backends
• created for specifying finer-grained queries
• provides interface between client and server
• client requests data from GraphQL server
• data requests are based on GraphQL queries
• => write queries against the schema
58. GraphQL versus REST
• a “finer-grained” alternative to REST
• REST is all-or-nothing: an “entity” is returned
• GraphQL returns a subset of elements of an “entity”
• Falcor from Netflix: alternative to GraphQL (no schema)
59. GraphQL: What it isn’t
• GQL does not dictate a server language
• GQL does not dictate a storage/back-end
• GQL is a query language without a database
60. GraphQL: What Does it Do?
• It exposes a single endpoint
• the endpoint parses and executes a query
• The query executes over a type system
• the type system is defined in the application server
• the type system is available via introspection (a GQL API)
61. GraphQL Server Structure
GraphQL servers have three components:
• 1) GraphQL “core” (JavaScript and other languages)
• 2) Type Definitions (maps app code to internal system)
• 3) Application code (business logic)
62. GraphQL Core: Five Components
• 1) Frontend lexer/parser: an AST [Relay uses parser]
• 2) Type System: GraphQLObjectType (a class)
• 3) Introspection: for querying types
• 4) Validation: is a query valid in the app’s schema?
• 5) Execution: manage query execution (via the AST)
63. The GraphiQL IDE
• https://github.com/skevy/graphiql-
app/blob/master/README.md
• https://github.com/skevy/graphiql-app/releases
• OSX: brew cask install graphiql
66. GraphQL Queries
• query EmpNameQuery {
• emp {
• fname
• lname
• }
• }
• The result of the preceding query is here:
• {
• "data": [
• "emp": {
• "fname": "John",
• "lname": "Smith"
• }
• ]
• }
67. GraphQL Websites
• Apollo: http://www.apollostack.com/
“consolidates” data (removes duplicates in a tree)
• Reindex: https://www.reindex.io/blog/redux-and-
relay
• Scaphold: scaphold.io
• Upcoming SF conference: http://graphqlsummit.com/
68. Angular 2 + Relay
• Relay: a “wrapper” around client-side components
• Data requests from a component “go through” Relay
• Relay sends data requests to a GraphQL server
• Data is returned to client application
• Data is displayed according to application code/logic
• Angular 2 works with Relay
70. Recent/Upcoming Books and Training
1) HTML5 Canvas and CSS3 Graphics (2013)
2) jQuery, CSS3, and HTML5 for Mobile (2013)
3) HTML5 Pocket Primer (2013)
4) jQuery Pocket Primer (2013)
5) HTML5 Mobile Pocket Primer (2014)
6) D3 Pocket Primer (2015)
7) Python Pocket Primer (2015)
8) SVG Pocket Primer (2016)
9) CSS3 Pocket Primer (2016)
10) Angular 2 Pocket Primer (2017)