1. Angular 2 for Beginners
Oswald Campesato
Consultant/Training:
www.iquarkt.com
ocampesato@yahoo.com
2. Features of Angular 2 (part 1)
• Beta status
• component-based architecture
• loosely coupled components
• less code more application focus
• "Mobile First" approach
• Angular 2 Github repository:
https://github.com/angular.io
3. Features of Angular 2 (part 2)
• Angular 2 can be 5x faster than Angular 1.x
• One-way data binding (by default)
• Two-way data binding (optional)
• Dependency injection
• Support for ES5/ES6/TypeScript
• Performance comparable to React(?)
4. Ang1.x features removed from Ang 2
+ $scope
+ factories
+ controllers
+ providers
+ $apply
+ $digest
+ many built-in directives
5. 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
7. 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)
8. Angular 2 and TypeScript
• TypeScript classes (transpiled to ES5)
• @ symbol for annotations/decorators
• @Component (selector, template, … )
• class MyApp{} (or some other name of your choice)
• Bootstrapping the ‘root’ component:
bootstrap(MyApp)
9. Angular 2 Example (app/main.ts)
• import {bootstrap} from 'angular2/platform/browser';
• import {Component} from 'angular2/core';
• @Component({
• selector: 'my-app',
• template: `<div>Hello from Angular 2</div>`
• })
• class MyApp {}
• bootstrap(MyApp);
11. Add Some Data (app/main.ts)
• import {bootstrap} from 'angular2/platform/browser';
• import {Component} from 'angular2/core';
• @Component({
• selector: 'my-app',
• template: `<div>{{ city }}</div>`
• })
• class MyApp {
• city:string;
• constructor() {
• this.city = ‘New York’;
• }
• }
• bootstrap(MyApp);
12. Exercise: Add More Data (main.ts)
• Add a first name field
• Add a last name field
• Add a state field
• reload the application
13. ng-repeat vs *ngFor
• Angular 1.x "ng-repeat":
<ul>
<li ng-repeat="user in users">
<h2>{{user}</h2>
</li>
</ul>
• Angular 2 "*ngFor":
<ul>
<li *ngFor="#user of users">
<h2>{{user}}</h2>
</li>
</ul>
14. Display List of Users (app/main.ts)
• import {bootstrap} from 'angular2/platform/browser';
• import {Component} from 'angular2/core';
• @Component({
• selector: 'my-app',
• template: `<div><ul>
• <li *ngFor='user of users'> {{ user }} </li>
• </ul></div>`
• })
• class MyApp {
• users:string[]; // or users:Array<string>;
• constructor() {
• this.users = ['Jane', 'Dave', 'Tom'];
• }
• }
• bootstrap(MyApp);
15. Exercise: Display User data with ngFor
• Modify the array to support literal objects
• Include first name/last name/city properties
• Display three properties in an unordered list
• reload the application
16. Angular 2 and Event Objects
• <button (click)="clicked($event)"></button>
@Component(...)
class MyApp {
clicked(event) {
event.preventDefault();
// do stuff here
console.log("you clicked me");
}
}
bootstrap(MyApp);
19. 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
20. ES6 let and Arrow Functions
• 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
21. ES6 Class Definition (part 1)
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea() {
return this.height * this.width;
}
}
• var r1 = new Rectangle(5,10);
• var r2 = new Rectangle(25,15);
22. 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:
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Classes
23. What is TypeScript?
• A superset of JavaScript (ES6): 10/01/2012
• A compiled language (tsc compiler)
• strong typing and also type inferencing
• 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
• TypeScript type definitions (update via "nuget"):
https://github.com/borisyankov/DefinitelyTyped
24. TypeScript Improvements over ES5
• Types
• Classes
• Annotations
• Imports
• language utilities (e.g. destructuring)
26. 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[] = [1, true, ”pizza"];
27. 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");
28. 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
29. 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
});
30. 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);
31. 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;
}
}
32. 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());
• Exercise: use an interface in class User
• Aside: use interfaces as arguments of public methods
(whenever possible) instead of using standard JS/TS types or
class instances
33. Convert JSON Data to TS Class (1)
• Consider the following array of data:
var people = [
{fname:"Jane",lname:"Smith",zip:"94043"},
{fname:"John",lname:"Jones",zip:"94539"},
{fname:"Dave",lname:"Starr",zip:"67800"}
]
34. Convert JSON Data to TS Class (2)
class People {
• public fname:string;
• public lname:string;
• public zip:string;
• constructor(public fname:string,
• public lname:string,
• public zip:string) {
• this.fname = fname;
• this.lname = lname;
• this.zip = zip;
• }
}
35. Convert JSON Data to TS Class (3)
• Array of TypeScript objects:
var TSPeople = [
new People("Jane","Smith","94043"),
new People("John","Jones","94539"),
new People("Dave","Starr","67800")
];
36. TypeScript and the this keyword
• The this keyword is contextually bound in the same
fashion as standard JS functions
• The this keyword is lexically bound in Lamba functions
so it’s automatically captured (emitted JS uses _this)
• Typically based on how the function is called
• More information about the this keyword:
https://tinyurl.com/MDNthis
37. Migrating JS "classes" to TypeScript
• Option #1: Annotate with an interface:
+Interface and impl are synchronized manually
+Faster initially and lower risk
• Option #2: Refactor as a class:
+More initial code changes
+More maintainable and semantic
http://www.typescriptlang.org/Handbook
38. What Should I Learn???
• Main features of ES6 and TypeScript 1.6+
• "basic" Angular 1.5+ and 2 (best practices)
• Practice converting code from ANG 1.x to 2
• 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, npmjs, gulp, grunt (older), broccoli,
+ webpack, browserify (older), jspm+systemjs
https://github.com/addyosmani/es6-tools
39. 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)
40. Browser Status for ES6
• Modern IE: https://goo.gl/56n7IL
• Mozilla: https://goo.gl/iSNDf9
• Chrome: https://www.chromestatus.com/features#ES6
43. Angular Tutorials
• Getting started with Angular 2:
https://docs.google.com/document/d/1MkpvTNfmxHwdSv9rQyQIvjR
LnoGk4rvkNMkOEWTPkCw/edit#heading=h.6z1yv9f94fuv
• Building Angular Apps using Flux:
https://docs.google.com/document/d/16axBamHEZORS_KJZDjahLuhk
hUuNVt77ZcGRoRiyjfQ/edit
New features in Angular 1.4:
• https://docs.google.com/document/d/1BkDxdkzB5JmQBgpLKEkGY
92pWF9Xr89cSLltPJVdHC0/edit
44. Future Work in Angular 2
• Server-side rendering
• Web Workers
• smooth and responsive UI
• Native mobile UI (see Ionic for mobile)
• Compile as build step
45. 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 Pocket Primer (2016)