Share
Embed
Introduction to Angular 2
Brief introduction to ECMAScript 2015, ECMAScript 2016, TypeScript and Angular 2.
If you want to practice your skills after completing the presentation, take a look at this exercise: https://github.com/mgechev/angular2-github-app-bootstrap
The slides and the exercise are based on Angular 2 alpha28.
Minko Gechev
June 29, 2015
Transcript
184 slides
-
Minko Gechev github.com/mgechev twitter.com/mgechev { "job": "Freelancer", "hobbies": [ "open
source", "blogging", "teaching", "sports" ], "communityEvents": [ "SofiaJS", "BeerJS Sofia" ] } -
– angular.io “Angular is a development platform for building mobile
and desktop web applications” -
ECMAScript 5 Property Descriptor Object.defineProperty(obj, 'name', { set: function (val)
{ console.log('Setting the value'); this._name = val; }, get: function (val) { console.log('Getting the value'); return this._name; } }); obj.name = 'foo'; console.log(obj.name); // Setting the value // Getting the value // foo -
ECMAScript 5 Property Descriptor Object.defineProperty(obj, 'name', { set: function (val)
{ console.log('Setting the value'); this._name = val; }, get: function (val) { console.log('Getting the value'); return this._name; } }); obj.name = 'foo'; console.log(obj.name); // Setting the value // Getting the value // foo -
ECMAScript 5 Property Descriptor Object.defineProperty(obj, 'name', { set: function (val)
{ console.log('Setting the value'); this._name = val; }, get: function (val) { console.log('Getting the value'); return this._name; } }); obj.name = 'foo'; console.log(obj.name); // Setting the value // Getting the value // foo -
ECMAScript 5 Property Descriptor Object.defineProperty(obj, 'name', { set: function (val)
{ console.log('Setting the value'); this._name = val; }, get: function (val) { console.log('Getting the value'); return this._name; } }); obj.name = 'foo'; console.log(obj.name); // Setting the value // Getting the value // foo -
ECMAScript 5 Property Descriptor Object.defineProperty(obj, 'name', { set: function (val)
{ console.log('Setting the value'); this._name = val; }, get: function (val) { console.log('Getting the value'); return this._name; } }); obj.name = 'foo'; console.log(obj.name); // Setting the value // Getting the value // foo -
ECMAScript 5 Property Descriptor Object.defineProperty(obj, 'name', { set: function (val)
{ console.log('Setting the value'); this._name = val; }, get: function (val) { console.log('Getting the value'); return this._name; } }); obj.name = 'foo'; console.log(obj.name); // Setting the value // Getting the value // foo -
“ES2015 classes are a simple sugar over the prototype- based
OO pattern…” Classes -
ECMAScript 6 Classes class Developer extends Person { constructor(name, language)
{ super(name); this._language = language; } get language() { return this._language; } set language(language) { this.doSomethingElse(); this._language = language; } talk() { super.talk(); console.log(`I'm a professional ${this.language} developer`); } } -
ECMAScript 6 Classes class Developer extends Person { constructor(name, language)
{ super(name); this._language = language; } get language() { return this._language; } set language(language) { this.doSomethingElse(); this._language = language; } talk() { super.talk(); console.log(`I'm a professional ${this.language} developer`); } } -
ECMAScript 6 Classes class Developer extends Person { constructor(name, language)
{ super(name); this._language = language; } get language() { return this._language; } set language(language) { this.doSomethingElse(); this._language = language; } talk() { super.talk(); console.log(`I'm a professional ${this.language} developer`); } } -
ECMAScript 6 Classes class Developer extends Person { constructor(name, language)
{ super(name); this._language = language; } get language() { return this._language; } set language(language) { this.doSomethingElse(); this._language = language; } talk() { super.talk(); console.log(`I'm a professional ${this.language} developer`); } } -
ECMAScript 6 Classes class Developer extends Person { constructor(name, language)
{ super(name); this._language = language; } get language() { return this._language; } set language(language) { this.doSomethingElse(); this._language = language; } talk() { super.talk(); console.log(`I'm a professional ${this.language} developer`); } } -
“Arrows are a function shorthand using the => syntax…Unlike functions,
arrows share the same lexical this as their surrounding code.” Arrow Functions -
“Arrows are a function shorthand using the => syntax…Unlike functions,
arrows share the same lexical this as their surrounding code.” Arrow Functions -
Arrow Functions [1, 2, 3, 4].reduce((a, c) => a +
c, 0); [1, 2, 3].map(c => c + 1); function Developer() { this.talk = () => { console.log(`I speak ${this._language} fluently`); }; } -
Arrow Functions [1, 2, 3, 4].reduce((a, c) => a +
c, 0); [1, 2, 3].map(c => c + 1); function Developer() { this.talk = () => { console.log(`I speak ${this._language} fluently`); }; } -
Arrow Functions [1, 2, 3, 4].reduce((a, c) => a +
c, 0); [1, 2, 3].map(c => c + 1); function Developer() { this.talk = () => { console.log(`I speak ${this._language} fluently`); }; } -
Arrow Functions [1, 2, 3, 4].reduce((a, c) => a +
c, 0); [1, 2, 3].map(c => c + 1); function Developer() { this.talk = () => { console.log(`I speak ${this._language} fluently`); }; } -
Functional lexical scope for (var i = 0; i <
10; i += 1) { var foo = i + 1; } console.log(typeof i); // number console.log(typeof foo); // number -
Local lexical scope for (let i = 0; i <
10; i += 1) { let foo = i + 1; } console.log(typeof i); // undefined console.log(typeof foo); // undefined -
Promises “Promises could be used instead of callbacks for handling
asynchronous actions. They are used as containers for resolving “future” values.” -
Promises fetch('/data.json') .then(data => { return data.json(); }, error =>
{ console.error(error); }) .then(json => doStuff(json)); -
Promises Promise.all([ fetch('/a.json'), fetch('/b.json'), fetch('/c.json') ]).then(res => { return Promise.all([
res[0].text(), res[1].text(), res[2].text() ]); }) .then(data => { console.log(data.join('')); }); -
Modules // Developer.js export default class Developer { // ...
} // app.js import Developer from './Developer'; // Math.js let log2 = Math.log2.bind(Math); let sin = Math.sin.bind(Math); export { log2, sin }; // app.js import * as math from './Math'; math.log2(10); -
Modules // Developer.js export default class Developer { // ...
} // app.js import Developer from './Developer'; // Math.js let log2 = Math.log2.bind(Math); let sin = Math.sin.bind(Math); export { log2, sin }; // app.js import * as math from './Math'; math.log2(10); -
Modules // Developer.js export default class Developer { // ...
} // app.js import Developer from './Developer'; // Math.js let log2 = Math.log2.bind(Math); let sin = Math.sin.bind(Math); export { log2, // same as log2: log2 sin }; // app.js import * as math from './Math'; math.log2(10); -
Module Loaders “Additional imperative API to the declarative module syntax,
which allows you to programmatically work with modules and configure the module loading.” -
– github.com/wycats/javascript-decorators “Decorators make it possible to annotate and modify
classes and properties at design time.” ES2016 Decorators -
Decorators @Aspect class LoggingAspect { @Before(/.*/, /.*/) before(args) { console.log(`${args.name}
called with ${args.args}`); } @After(/.*/, /.*/) after(args) { console.log(`${args.name} execution completed`); } @OnThow(/.*/, /.*/) errorHandler(args) { console.error(`${args.name} threw an error`, args.error); } } -
Decorators @Aspect class LoggingAspect { @Before(/.*/, /.*/) before(args) { console.log(`${args.name}
called with ${args.args}`); } @After(/.*/, /.*/) after(args) { console.log(`${args.name} execution completed`); } @OnThow(/.*/, /.*/) errorHandler(args) { console.error(`${args.name} threw an error`, args.error); } } -
TypeScript • Superset of ECMAScript • Allows optional static typing
• Better support by text editors/IDEs • Reduce bugs • Faster code -
TypeScript Class class Developer { age:string; constructor(private languages:string[], private name:string,
age) { this.age = (age).toString(2); } private codeInPHP() { // body } public writeSoftware() { // body } public coffeeBreak(nextTask:{(name:string):void}) { setTimeout(nextTask, 1000); } } -
TypeScript Class class Developer { age:string; constructor(private languages:string[], private name:string,
age) { this.age = (age).toString(2); } private codeInPHP() { // body } public writeSoftware() { // body } public coffeeBreak(nextTask:{(name:string):void}) { setTimeout(nextTask, 1000); } } -
TypeScript Class class Developer { age:string; constructor(private languages:string[], private name:string,
age) { this.age = (age).toString(2); } private codeInPHP() { // body } public writeSoftware() { // body } public coffeeBreak(nextTask:{(name:string):void}) { setTimeout(nextTask, 1000); } } -
TypeScript Class class Developer { age:string; constructor(private languages:string[], private name:string,
age) { this.age = (age).toString(2); } private codeInPHP() { // body } public writeSoftware() { // body } public coffeeBreak(nextTask:{(name:string):void}) { setTimeout(nextTask, 1000); } } -
TypeScript Class class Developer { age:string; constructor(private languages:string[], private name:string,
age) { this.age = (age).toString(2); } private codeInPHP() { // body } public writeSoftware() { // body } public coffeeBreak(nextTask:{(name:string):void}) { setTimeout(nextTask, 1000); } } -
TypeScript Class class Developer { age:string; constructor(private languages:string[], private name:string,
age) { this.age = (age).toString(2); } private codeInPHP() { // body } public writeSoftware() { // body } public coffeeBreak(nextTask:{(name:string):void}) { setTimeout(nextTask, 1000); } } -
Interfaces interface A { foo():void; bar(a:number):string; } interface B {
baz(a:string):string } interface C extends A, B { } class D implements C { // ... } -
Interfaces interface A { foo():void; bar(a:number):string; } interface B {
baz(a:string):string } interface C extends A, B { } class D implements C { // ... } -
Interfaces interface A { foo():void; bar(a:number):string; } interface B {
baz(a:string):string } interface C extends A, B { } class D implements C { // ... } -
Interfaces interface A { foo():void; bar(a:number):string; } interface B {
baz(a:string):string } interface C extends A, B { } class D implements C { // ... } -
Type Inference let answer = 42; let callback:{(a:number, ...nums:any[]):number}; callback
= (a, nums) => nums.reduce((a, c) => a + c, a); let foo; foo = 42; -
Type Inference let answer = 42; let callback:{(a:number, ...nums:any[]):number}; callback
= (a, nums) => nums.reduce((a, c) => a + c, a); let foo; foo = 42; -
Type Inference let answer = 42; let callback:{(a:number, ...nums:any[]):number}; callback
= (a, nums) => nums.reduce((a, c) => a + c, a); let foo; foo = 42; -
Type Inference let answer = 42; let callback:{(a:number, ...nums:any[]):number}; callback
= (a, nums) => nums.reduce((a, c) => a + c, a); let foo; foo = 42; -
Ambient Declarations interface JQueryStatic { /** * Perform an asynchronous
HTTP (Ajax) request. * * @param settings A set of key/value pairs that … */ ajax(settings: JQueryAjaxSettings): JQueryXHR; /** * Perform an asynchronous HTTP (Ajax) request. * * @param url A string containing the URL to which the request is sent. * @param settings A set of key/value pairs that… */ ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; // ... } declare var jQuery: JQueryStatic; declare var $: JQueryStatic; -
Add Type Definition Reference /// <reference path="jQuery.d.ts" /> let elems
= $('.elems'); //... -
Annotations import {Component, View, NgFor} from 'angular2/angular2'; import {Home} from
'./components/home/home'; import {About} from './components/about/about'; @Component({ selector: 'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html?v=<%= VERSION %>', directives: [RouterOutlet, RouterLink] }) class App {} -
Annotations import {Component, View, NgFor} from 'angular2/angular2'; import {Home} from
'./components/home/home'; import {About} from './components/about/about'; @Component({ selector: 'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html?v=<%= VERSION %>', directives: [RouterOutlet, RouterLink] }) class App {} -
UserDetails.ts import {Component, View} from ‘angular2/angular2'; import {NgIf} from 'angular2/angular2';
@Component({ selector: 'user-details', properties: ['user'] }) @View({ templateUrl: ‘./user-details.html’, directives: [NgIf] }) export class UserDetails { user:any; constructor() {} } -
UserDetails.ts import {Component, View} from ‘angular2/angular2'; import {NgIf} from 'angular2/angular2';
@Component({ selector: 'user-details', properties: ['user'] }) @View({ templateUrl: ‘./user-details.html’, directives: [NgIf] }) export class UserDetails { user:any; constructor() {} } -
UserDetails.ts import {Component, View} from ‘angular2/angular2'; import {NgIf} from 'angular2/angular2';
@Component({ selector: 'user-details', properties: ['user'] }) @View({ templateUrl: ‘./user-details.html’, directives: [NgIf] }) export class UserDetails { user:any; constructor() {} } -
Service.ts @Injectable() export class Http { constructor(private _backend: XHRBackend, private
_defaultOptions: BaseRequestOptions) {} get(url: string, options?: IRequestOptions) { return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) .merge({method: RequestMethods.GET}))); } post(url: string, body: any, options?: IRequestOptions) { return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) .merge({body: body, method: RequestMethods.POST}))); } } -
Service.ts @Injectable() export class Http { constructor(private _backend: XHRBackend, private
_defaultOptions: BaseRequestOptions) {} get(url: string, options?: IRequestOptions) { return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) .merge({method: RequestMethods.GET}))); } post(url: string, body: any, options?: IRequestOptions) { return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) .merge({body: body, method: RequestMethods.POST}))); } } -
Service.ts @Injectable() export class Http { constructor(private _backend: XHRBackend, private
_defaultOptions: BaseRequestOptions) {} get(url: string, options?: IRequestOptions) { return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) .merge({method: RequestMethods.GET}))); } post(url: string, body: any, options?: IRequestOptions) { return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) .merge({body: body, method: RequestMethods.POST}))); } } -
Detection mechanisms • No front-end state • Event based •
Difference based • Dirty checking -
A B E D C Page Body Header Content Sidebar
Page Body Header Content Sidebar -
addWatcher({ last: eval('user.name'); exp: 'user.name', fn: result => { element.text(result);
} }); <section> <span>{{user.name}}</span> </section> -
Dirty Checking let digest = (component) => { let dirty,
watcher, current, i; let { watchers, children } = component; do { dirty = false; for (i = 0; i < watchers.length; i++) { watcher = watchers[i]; current = eval(watcher.exp); if (!equals(watcher.last, current)) { watcher.last = clone(current); dirty = true; watcher.fn(current); } } } while (dirty); for (i = 0; i < children.length; i++) digest(children[i]); }; -
Dirty Checking let digest = (component) => { let dirty,
watcher, current, i; let { watchers, children } = component; do { dirty = false; for (i = 0; i < watchers.length; i++) { watcher = watchers[i]; current = eval(watcher.exp); if (!equals(watcher.last, current)) { watcher.last = clone(current); dirty = true; watcher.fn(current); } } } while (dirty); for (i = 0; i < children.length; i++) digest(children[i]); }; -
Dirty Checking let digest = (component) => { let dirty,
watcher, current, i; let { watchers, children } = component; do { dirty = false; for (i = 0; i < watchers.length; i++) { watcher = watchers[i]; current = eval(watcher.exp); if (!equals(watcher.last, current)) { watcher.last = clone(current); dirty = true; watcher.fn(current); } } } while (dirty); for (i = 0; i < children.length; i++) digest(children[i]); }; -
Dirty Checking let digest = (component) => { let dirty,
watcher, current, i; let { watchers, children } = component; do { dirty = false; for (i = 0; i < watchers.length; i++) { watcher = watchers[i]; current = eval(watcher.exp); if (!equals(watcher.last, current)) { watcher.last = clone(current); dirty = true; watcher.fn(current); } } } while (dirty); for (i = 0; i < children.length; i++) digest(children[i]); }; -
Dirty Checking let digest = (component) => { let dirty,
watcher, current, i; let { watchers, children } = component; do { dirty = false; for (i = 0; i < watchers.length; i++) { watcher = watchers[i]; current = eval(watcher.exp); if (!equals(watcher.last, current)) { watcher.last = clone(current); dirty = true; watcher.fn(current); } } } while (dirty); for (i = 0; i < children.length; i++) digest(children[i]); }; -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val; }); -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val; }); -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val + 1; }); -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val + 1; }); -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val + 1; }); -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val + 1; }); -
Two-way binding input.onchange = () => { component[property] = input.value;
digest(); }; addWatcher(property, (val) => { input.value = val + 1; }); -
unbuffer x | unbuffer command done find echo echo Pipes
find ls ls command # process each line, using variables as parsed into $var1, $var2, etc # (note that this may be a subshell: var1, var2 etc will not be available # after the while loop terminates; some shells, such as zsh and newer # versions of Korn shell, process the commands to the left of the pipe # operator in a subshell) done -
Pipe Interface export interface Pipe { supports(obj): boolean; onDestroy(): void;
transform(value: any): any; } -
Pipes A way of extending the change detection • Format
data • Perform smarter change detection -
Dynamic Change Detector _pipeCheck(proto: ProtoRecord, throwOnChange: boolean) { // ...
var currValue = pipe.transform(context); if (!isSame(prevValue, currValue)) { // ... this._setChanged(proto, true); return change; } else { // ... this._setChanged(proto, true); return null; } } else { // ... this._setChanged(proto, false); return null; } } -
Pipes A few examples: • IterableChanges • PromisePipe • UpperCasePipe
• ObservablePipe • JsonPipe -
IterableDiff (foreach.js) set ngForOf(value: any) { this._ngForOf = value; this._pipe
= this.pipes .get("iterableDiff",…); } -
Router import {RouteConfig, RouterOutlet, RouterLink, routerInjectables} from 'angular2/router'; @Component({ selector:
'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html', directives: [RouterOutlet, RouterLink] }) class App {} bootstrap(App, [routerInjectables]); -
Router import {RouteConfig, RouterOutlet, RouterLink, routerInjectables} from 'angular2/router'; @Component({ selector:
'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html', directives: [RouterOutlet, RouterLink] }) class App {} bootstrap(App, [routerInjectables]); -
Router import {RouteConfig, RouterOutlet, RouterLink, routerInjectables} from 'angular2/router'; @Component({ selector:
'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html', directives: [RouterOutlet, RouterLink] }) class App {} bootstrap(App, [routerInjectables]); -
Router import {RouteConfig, RouterOutlet, RouterLink, routerInjectables} from 'angular2/router'; @Component({ selector:
'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html', directives: [RouterOutlet, RouterLink] }) class App {} bootstrap(App, [routerInjectables]); -
Router import {RouteConfig, RouterOutlet, RouterLink, routerInjectables} from 'angular2/router'; @Component({ selector:
'app' }) @RouteConfig([ { path: '/', component: Home, as: 'home' }, { path: '/about', component: About, as: 'about' } ]) @View({ templateUrl: './app.html', directives: [RouterOutlet, RouterLink] }) class App {} bootstrap(App, [routerInjectables]); -
Router Directives <section class="sample-app-content"> <nav> <a router-link="home">Home</a> <a router-link="about">About</a> </nav>
<router-outlet></router-outlet> </section> -
Router Directives <section class="sample-app-content"> <nav> <a router-link="home">Home</a> <a router-link="about">About</a> </nav>
<router-outlet></router-outlet> </section> -
Router Directives <section class="sample-app-content"> <nav> <a router-link="home">Home</a> <a router-link="about">About</a> </nav>
<router-outlet></router-outlet> </section> -
References • Angular 2 Official Website • Change And Its
Detection In JavaScript Frameworks • Angular2 - First Impressions • ng-conf 2015 Keynote 2 - Misko Hevery and Rado Kirov • angular2-seed • angular2-education