Angular 2の失敗しない始め方

A Way for Happy Angular Days

Suguru Inatomi @laco0416
ng-japan 2016

About me

laco

Agenda

  • FAQ and Misunderstanding
  • Angular 2 Fundamental
  • Things to Learn Angular 2

FAQ and Misunderstanding

the Fact

Q. "AngularJS 2?"

"AngularJS 2"

"Angular" contains ...

  • Framework library
  • Browser/Web Worker/Electron/Native/...
  • Server-side
  • CLI
  • ...

"Angular" = Platform

Q. "I MUST learn TypeScript?"

you SHOULD

Why TypeScript?

  • Static type checking
  • Decorators
  • Type-base DI

Static Types

Types as API documents

  • Always correct
  • Compiler check
  • Generics: Type-safe collection
  • Auto-completions

@Decorators()

Next generation standard

Spec: javascript-decorators
Status: tc39/ecma262

  • Class and Property: Stage 1
  • Function: Stage 0
  • Method: Stage 0

tsc --experimentalDecorators

Component definition (ES5)

var ProfileComponent = ng.core.Component({
    selector: "app-profile",
    template: "<p>Name: {{ name }}</p>"
}).Class({
    constructor: function() {
        this.name = "laco";
    }
});

Component definition (TS)

@Component({
    selector: "app-profile",
    template: "<p>Name: {{ name }}</p>"
})
class ProfileComponent {
    name: string;
    constructor() {
        this.name = "laco";
    }
}

Type-base DI

IOW, "Typo-safe" DI
import {Http} from "angular2/http";

@Injectable()
class MyService {
    constructor(private anyNameForHttp: Http) {
    }
}

Good-bye "$http"

Angular 2 with TypeScript

Safe & Productive

"Why don't you use TypeScript?"

Q. "Angular 1.x will die?"

Don't worry!

  • 1.4.x, 1.5.x : Stable
  • =<1.6 : Latest

No new feature
Migration support

Component Helper


angular.module("myApp")
    .component("myComponent", {...});

<my-component></my-component>
Sugar for migration
  • Directive wrapper
  • Best practice of v1.x

Component Router


$routeConfig: [
    { path: '/a/b/c', component: 'myComponent' },
    ...
]
  • Same API as "angular2/router"
  • npm i -S angular@1.5.x @angular/router

Q. "Two-way binding is gone?"

No

But Changed

ng-model

<input ng-model="myName">
<span>{{ myName }}</span>

Two-way Data-binding

[(ngModel)]

<input [(ngModel)]="myName">

<input [ngModel]="myName"
    (ngModelChange)="myNameChanged($event)">

Sugar of One-way + Event handler

  • Explicit Syntax: [()]
  • Simple API

Q. "dirty-checking yet?"

Yes

Get Performance

Code Generate

Angular generates VM friendly code

  • on bootstrapping
  • Component specific checker: Change Detector
  • 100000 checks / ~10 ms

Don't worry number of $watch!

Q. "Server-side rendering?"

Yes

But not yet

Angular Universal


angular/universal

Angular 2 for Node.js

Angular Universal

  • One of the Angular Project
  • Run on Node.js
  • Same API as on Browser: "angular2/core"
  • Can Reuse Components
Full Stack Angular 2 – Jeff Whelpley and Patrick Stapleton - YouTube

In the future...

Node.js / Java / PHP / .Net / Python / ...

Q. "Using Web Components?"

No

But you can

Use ShadowDOM

ViewEncapsulation

@Component({
    selector: "my-component",
    encapsulation: ViewEncapsulation.Native
})
class MyComponent{}

Default: ViewEncapsulation.Emulated

ViewEncapsulation.Emulated

ViewEncapsulation.Native

Q. "I want to know XXX"

Please ask me later!!

Angular 2 Fundamental

"What's this?"

  • SystemJS
  • RxJS
  • Zone.js
  • reflect-metadata

SystemJS

Dynamic Module Loader
systemjs/systemjs

  • Loads modules in Runtime
  • For Lazy Loading
  • Polyfill for Browser Loader

SystemJS is NOT required

  • Used for Bundled JS
  • npm package never requires SystemJS
  • You can use Browserify / Webpack / JSPM / ...

RxJS


Reactive Programming in JavaScript
ReactiveX/RxJS

  • Polyfill for Observable
  • Useful Operators
  • "Lodash for Async"

Observable

Next generation standard

Spec: es-observable
Status: tc39/ecma262

  • Proposal: Stage 1
  • Sequential Async Data

Observable vs Promise

  • Multiple vs Once
  • Cancelable vs Uncancelable
  • Writable vs Read-only
  • Lazy vs Not Lazy

Async on the Web

  • DOM Events : Multiple
    <input onkeyup="...">
  • Animations : Cancelable
    element.animate(...).cancel()
  • WebSockets : Multiple
    connection.onmessage(e=>...)
  • Ajax : Cancelable
    xhr.abort()

Zone.js

Polyfill for Zones

Zones

Next generation standard

Spec: Zones
Status: tc39/ecma262

  • Proposal: Stage 0
  • a logical asynchronous context
  • Events: beforeTask(), afterTask(), ...

Zones

zone.fork({
    onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
        try {
            console.log("before")
            return delegate.invokeTask(target, task, applyThis, applyArgs);
        } finally {
            console.log("after");
        }
    }
}).run(() => {
    setTimeout(() => { console.log("task"); }, 0);
});

Changes

Changes happens in ...:

  • XHR: Ajax responce
  • Timer: setTimeout(), setInterval()
  • View Events: click, submit

Async tasks Changes
=> Angular watches all task

reflect-metadata

Next generation standard
  • Reflection for Decorators
  • Component metadata from Decorator

tsc --emitDecoratorMetadata

Things to Learn Angular 2

How to get happy Angular days

ng2 = ng1.add( XXX );

XXX = Simplicity

Angular 1

ngClick, ngKeydown, ngKeyup, ngBlur, ngMaxLength, ngMinLength, ngMouseOver, ngMouseLeave, ngBind, ngFocus, ...

.directive(), .controller(), .service(), .factory(), .constant(), .config(), ...

Angular 2

Things to remember

Properties: <input [value]="userName">

Events: <button (click)="send($event)">...</button>

Two-way: <input [(ngModel)]="userName">

Component: @Component

XXX = Performance

Angular 1 =
  • dirty-checking
  • two-way bindings
  • $digest loop

Change Detection

thoughtram Blog
日本語訳
Strategy for rendering

What's Change Detection?

Model => View Projection

Check changes

  • Every component has own CD
  • 100000 checks / 10ms
  • Change Detectors Tree:

One-way checking

ChangeDetectionStrategy

Should I update my view?
ng2 = ng1.add(XXX)
  • Simplicity
  • Performance
  • ???

XXX = Toolability

Tooling

Static tools
  • Compilers
  • Linters
  • IDEs
Dynamic tools
  • Unit tests
  • Browser console
  • Batarang

"Analyzability"

Angular 1
<my-directive
    prop1="ctrl.someProp"
    prop2="some text">
</my-directive>

Expression? Text?

Angular 2

<my-directive
    [prop1]="someProp"
    prop2="some text">
</my-directive>

Static Analyzable

Things to learn

Angular on the (Next) Web Standards

  • ES2015
  • Decorators
  • Observables
  • Zones

To Learn: Angular feature < Web Standards

"looks like a different library..."

Yes

Everything changes.

Understand the Web

The Web has moved

Frameworks must move

Martin Probst - Awesome Productivity with Angular 2 - YouTube

Keep Learning

Coming soon

  • ES2016 / ES.next
  • Web Components
  • Web Animations
  • Module Loader
  • ServiceWorker
  • ...

Nothing was achieved in the comfort zone

Todd Motto - Which Way Is Up? // Speaker Deck

Not to Know Everything

OK!

But Keep an eye on it!

Not to Use the Latest Staff

OK!

But Keep an eye on it!

Keep using Angular 1

OK!!

Keep an eye on Angular 2!

Try to use Angular 2

Great!

but Don't Forget

Angular 2 is BETA

Watch CHANGELOG

More: Watch Commits

More...?

Let's Contribute

Send Issues

Send Patches

My First PR

Don't scare Open Source

  • Have Confidence
  • Keep Learning
  • Keep Creating
  • Keep Improving

You can also...

  • Join a Conference (just now!)
  • Go to Meetup
  • Write Articles
  • Discuss on SNS

Everyone has Something to Teach Others

Angular is a Platform

Angular on
Next Generation Standards

Understand the Web

Keep Learning

Nothing
was Achieved
in the
Comfort Zone

Let's Contribute!

Enjoy Learning!

Have a
Happy Angular Day!

Thanks!

Suguru Inatomi @laco0416
ng-japan 2016
http://goo.gl/TeM0Fr