chtijug - introduction à angular2

85
Angular 2 @EmmanuelDemey

Upload: demey-emmanuel

Post on 16-Apr-2017

945 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: ChtiJUG - Introduction à Angular2

Angular 2@EmmanuelDemey

Page 2: ChtiJUG - Introduction à Angular2

Emmanuel

DEMEYConsultant & Formateur Web

Zenika Nord

@EmmanuelDemey

Web / Domotique / Histoire / Biérologie

Page 3: ChtiJUG - Introduction à Angular2
Page 4: ChtiJUG - Introduction à Angular2

Les choses que nous n'aimons pas...

Page 5: ChtiJUG - Introduction à Angular2

Architecture AngularJS

MV* MV* MV*

Page 6: ChtiJUG - Introduction à Angular2

Architecture AngularJS

MV* MV* MV*

Page 7: ChtiJUG - Introduction à Angular2

Architecture AngularJS

DI (provider, service, factory...)

MV* MV* MV*

Page 8: ChtiJUG - Introduction à Angular2

Architecture AngularJS

DI (provider, service, factory...)

MV* MV* MV*

Filtres

Page 9: ChtiJUG - Introduction à Angular2

Architecture AngularJS

DI (provider, service, factory...)

MV* MV* MV*

Filtres

Page 10: ChtiJUG - Introduction à Angular2

API des Directivesapp.directive('MyDirective', function(){ return { restrict: 'AE', require: '?^^ngModel', scope: { variable: '@' }, compile: function(...) { return { pre: function(...) { ... }, post: function(...) { ... } } }, link: function(...) { ... } }});

Page 11: ChtiJUG - Introduction à Angular2

app.directive('MyDirective', function(){ return { restrict: 'AE', require: '?^^ngModel', scope: { variable: '@' }, compile: function(...) { return { pre: function(...) { ... }, post: function(...) { ... } } }, link: function(...) { ... } }});

API des Directives

Page 12: ChtiJUG - Introduction à Angular2

app.directive('MyDirective', function(){ return { restrict: 'AE', require: '?^^ngModel', scope: { variable: '@' }, compile: function(...) { return { pre: function(...) { ... }, post: function(...) { ... } } }, link: function(...) { ... } }});

API des Directives

Page 13: ChtiJUG - Introduction à Angular2

app.directive('MyDirective', function(){ return { restrict: 'AE', require: '?^^ngModel', scope: { variable: '@' }, compile: function(...) { return { pre: function(...) { ... }, post: function(...) { ... } } }, link: function(...) { ... } }});

API des Directives

Page 14: ChtiJUG - Introduction à Angular2

<input ng-model="firstName">

<p> {{firstName }}</p>

2-way data-binding

Page 15: ChtiJUG - Introduction à Angular2

<input ng-model="firstName" ng-model-options="options"><p> {{firstName }}</p>

2-way data-binding

Page 16: ChtiJUG - Introduction à Angular2

<input ng-model="firstName">

<p> {{::firstName }}</p>

2-way data-binding

Page 17: ChtiJUG - Introduction à Angular2

Et ce n'est pas fini...

Page 18: ChtiJUG - Introduction à Angular2

Mais aussi...

Pas de Server-Side Rendering

Gestion des événements (ngClick, ...)

Gestion des attributs HTML (ngSrc, ...)

Page 19: ChtiJUG - Introduction à Angular2

La solution... Angular 2

Page 20: ChtiJUG - Introduction à Angular2

Attention !

Page 21: ChtiJUG - Introduction à Angular2

Version Alpha

P(eu|as) de Doc

Page 22: ChtiJUG - Introduction à Angular2

Architecture

Composants

Injection de Dépendance

Pipes

Page 23: ChtiJUG - Introduction à Angular2

Architecture Angular 2

<app></app>

Page 24: ChtiJUG - Introduction à Angular2

Architecture Angular 2

<app></app>

menu grid

gallery

Page 25: ChtiJUG - Introduction à Angular2

Architecture Angular 2

<app></app>

menu grid

gallery

DI

(classes ES6 ou TypeScript)

Pipes

(classes ES6 ou TypeScript)

Page 26: ChtiJUG - Introduction à Angular2

La Famille JavaScript

Page 27: ChtiJUG - Introduction à Angular2

La Famille JavaScript

ES5

Page 28: ChtiJUG - Introduction à Angular2

La Famille JavaScript

ES5

ES2015

Page 29: ChtiJUG - Introduction à Angular2

La Famille JavaScript

ES5

ES2015

Page 30: ChtiJUG - Introduction à Angular2

La Famille JavaScript

ES5

ES2015

TypeScript

Page 31: ChtiJUG - Introduction à Angular2

Les Web Components

Custom Elements Templates Imports Shadow DOM

Page 32: ChtiJUG - Introduction à Angular2

Les composants

Page 33: ChtiJUG - Introduction à Angular2

Composants Angular 2

Ressources de base en Angular 2

Tout est composant

Application représentée par un arbre

de composants

Utilisation de métadonnées pour

configurer un composant

Page 34: ChtiJUG - Introduction à Angular2

//<my-app></my-app>function MyAppComponent() {

}

MyAppComponent.annotations = [ new angular.ComponentAnnotation({ selector: 'my-app' }), new angular.ViewAnnotation({ template: "<main>" + "<h1> This is my first Angular2 app</h1>" + "</main>" })];

Composant version ES5

Page 35: ChtiJUG - Introduction à Angular2

import {Component, View} from 'angular2/angular2';

@Component({selector: 'my-app'})@View({ template: `<main> <h1> This is my first Angular2 app</h1> </main>`})class MyAppComponent {

}

Composant version TypeScript

Page 36: ChtiJUG - Introduction à Angular2

import {Component, View, bootstrap} from 'angular2/angular2';@Component({selector: 'my-app'})@View({ template: `<main> <h1> This is my first Angular2 app</h1> </main>`})class MyAppComponent {

}bootstrap(MyAppComponent);

Bootstrap de l'Application

Page 37: ChtiJUG - Introduction à Angular2

Binding

Root Cpt

Child1 Cpt Child2 Cpt

[property]="expression"(event)="update()"

Page 38: ChtiJUG - Introduction à Angular2

Property Binding

<input [attr]="expression" />

Accès à toutes les propriétés des éléments

HTML

Possibilité de définir de nouvelles propriétés

Compatibilité avec d'autres spécifications

Page 39: ChtiJUG - Introduction à Angular2

Property Binding

<body> <h1>My First Angular2 app</h1></body>

Page 40: ChtiJUG - Introduction à Angular2

Property Binding

<body> <h1 [textContent]="'My First Angular2 app'"> </h1></body>

Page 41: ChtiJUG - Introduction à Angular2

Property Binding

<body> <h1>{{'My First Angular2 app'}} </h1></body>

Page 42: ChtiJUG - Introduction à Angular2

Property Binding//<beerItem [beer]="'Maredsous'"></beerItem>@Component({ selector: 'beerItem', properties: ['beer']})@View({ template: `<section> <h2>{{beer}}</h2> <button>Je veux celle-ci !</button> </section>`})class BeerItem { beer: String;}

Page 43: ChtiJUG - Introduction à Angular2

Event Binding

<input (event)="expression" />

Accès à tous les événements des éléments

HTML

Possibilité de définir de nouveaux événements

Page 44: ChtiJUG - Introduction à Angular2

Event Bindings//<beerItem [beer]="'Maredsous'" (selectBeer)="sendToBeerTap()"></beerItem>@Component({ selector: 'beerItem', properties: ['beer'], events: ['selectBeer']})@View({ template: `<section> <h2>{{beer<}}</h2> <button (click)="selectItem()">Je veux celle-ci !</button> </section>`})class BeerItem { beer: String; selectBeer: EventEmitter; selectItem() { this.selectBeer.next(this.beer); }}

Page 45: ChtiJUG - Introduction à Angular2

Syntaxe valide ?

Page 46: ChtiJUG - Introduction à Angular2

“ Attribute names must consist of one or

more characters other than the space

characters, U+0000 NULL, """, "'", ">", "/",

"=", the control characters, and any

characters that are not defined by Unicode.

Syntaxe valide ?

Page 47: ChtiJUG - Introduction à Angular2

Syntaxe valide ?

Page 48: ChtiJUG - Introduction à Angular2

Component Dependency

Nécessité d'importer les composants

nécessaires à votre application

Propriété directives de @View

Erreur si composants non utilisés

Page 49: ChtiJUG - Introduction à Angular2

Component Dependencyimport {Component, View, bootstrap, NgFor} from 'angular2/angular2';import {BeerItem} from 'BeerItem';

@Component({ selector: 'my-app'})@View({ template: `<main class="mdl-layout__content"> <ul class="googleapp-card-list"> <li *ng-for="#beer of beers"> <beerItem [beer]="beer"></beerItem> </li> </ul> </main>`, directives: [NgFor, BeerItem]})class MyAppComponent { public beers: String[] = []; constructor() { ... }}

Page 50: ChtiJUG - Introduction à Angular2
Page 51: ChtiJUG - Introduction à Angular2

Support des

WebComponents

Page 52: ChtiJUG - Introduction à Angular2

WebComponents

@Component({ })@View({ template: string, templateUrl: string, encapsulation?: ViewEncapsulation, directives?: List<any>, styles?: List<string>, styleUrls?: List<string>,})class BeerItem { }

Page 53: ChtiJUG - Introduction à Angular2

WebComponents//From modules/angular2/src/core/render/api.ts

/** * How the template and styles of a view should be encapsulated. */export enum ViewEncapsulation { /** * Emulate scoping of styles by preprocessing the style rules * and adding additional attributes to elements. This is the default. */ Emulated, /** * Uses the native mechanism of the renderer. For the DOM this means creating a * ShadowRoot. */ Native, /** * Don't scope the template nor the styles. */ None}

Page 54: ChtiJUG - Introduction à Angular2

Injection de Dépendance

Page 55: ChtiJUG - Introduction à Angular2

Injection de Dépendances

Code métier dans des services

Chaque Service est un singleton

Principe d'Hollywood

Multiples implémentations en NG1 !

Page 56: ChtiJUG - Introduction à Angular2

Injection de Dépendances

app.service('TapService', function($http){ this.getBeer = function(beerId){ return $http.get('/api/i-am-thirsty/' + beerId); };});

app.controller('AppCtrl', function(TapService){ this.selectBeer = function(idBeer){ return TapService.getBeer(idBeer); }});

Page 57: ChtiJUG - Introduction à Angular2

DI version Angular2

1 Injecteur principal + 1 Injecteur par composant

Hérite de l'injecteur parent

Possibilité de redéfinir le Service à injecter

Utilisation d'annotations en ES6 et des types en

TypeScript

Services disponibles via le constructeur du

composant

Page 58: ChtiJUG - Introduction à Angular2

Injecteur Principal - toValue

@Component({selector: 'my-app'})@View({ template: `<main> <h1> Welcome to our {{breweryName}}</h1> </main>`})class MyAppComponent { constructeur(private breweryName:String) { ... }}

bootstrap(MyAppComponent, [bind(String).toValue('Zenika Brewery')]);

Page 59: ChtiJUG - Introduction à Angular2

Injecteur Principal - toClass

@Component({selector: 'my-app'})@View({ template: `<main> <h1> Welcome to our {{breweryName}}</h1> </main>`})class MyAppComponent { constructeur(private breweryService:BreweryService) { this.breweryName = this.breweryService.getBreweryName(); }}

bootstrap(MyAppComponent, [bind(BreweryService).toClass(BreweryService)]);

Page 60: ChtiJUG - Introduction à Angular2

Injecteur Principal - toClass

@Component({selector: 'my-app'})@View({ template: `<main> <h1> Welcome to our {{breweryName}}</h1> </main>`})class MyAppComponent { constructeur(private breweryService:BreweryService) { this.breweryName = this.breweryService.getBreweryName(); }}

bootstrap(MyAppComponent, [BreweryService]);

Page 61: ChtiJUG - Introduction à Angular2

Injecteur Principal -

toFactory@Component({selector: 'my-app'})@View({ template: `<main> <h1> Welcome to our {{breweryName}}</h1> </main>`})class MyAppComponent { constructeur(public breweryName:String) { ... }}

bootstrap(MyAppComponent, [bind(String) .toFactory((BreweryService) => { return BreweryService.getBreweryName(); }, [BreweryService])]);

Page 62: ChtiJUG - Introduction à Angular2

Child Injector@Component({selector: 'my-app'})@View({ template: `<main> <welcome-message></welcome-message> </main>`, directives: [WelcomeMessage]})class MyAppComponent { constructeur(public breweryName:String) { ... }}

bootstrap(MyAppComponent, [bind(String).toValue('Zenika Brewery')]);

Page 63: ChtiJUG - Introduction à Angular2

Child Injector

@Component({ selector: 'welcome-message'})@View({ template: `<h1>Welcome to our {{breweryName}}</h1>`})class WelcomeMessage { constructeur(public breweryName:String) { ... }}

Page 64: ChtiJUG - Introduction à Angular2

Child Injector

@Component({ selector: 'welcome-message'})@View({ template: `<h1>Welcome to our {{breweryName}}</h1>`, bindings: [ bind(String).toValue('Awesome Zenika Brewery') ]})class WelcomeMessage { constructeur(public breweryName:String){ ... }}

Page 65: ChtiJUG - Introduction à Angular2

Pipes

Page 66: ChtiJUG - Introduction à Angular2

Petit Rappel

{{ collectionOfBeers | orderBy:'note' | limitTo:5 }}

Page 67: ChtiJUG - Introduction à Angular2

Pipes

Identiques aux filtres d'AngularJS 1

Permet de manipuler une donnée

Utilisation d'une classe annotée @Pipe

Pipes disponibles dans le framework :

upperCase, lowerCase, Async,

Number, limitTo, json et date

Page 68: ChtiJUG - Introduction à Angular2

Pipes

import {Pipe, PipeTransform} from 'angular2/angular2';

@Pipe({ name: 'UpperCasePipe'})export class UpperCasePipe implements PipeTransform { transform(value: String, args: any[]) { return value.toUpperCase(); }}

Page 69: ChtiJUG - Introduction à Angular2

Pipes

import {Component, View} from 'angular2/angular2';import {UpperCasePipe} from './UpperCasePipe.ts'

@Component({ selector: 'widget1'})@View({ template: `<div>{{'Démo utilisant les pipes' | UpperCasePipe}}</div>`, pipes: [UpperCasePipe]})export class Widget1{}

Page 70: ChtiJUG - Introduction à Angular2

Pipesimport {Component, View} from 'angular2/angular2';import {UpperCasePipe} from './UpperCasePipe.ts'

@Component({ selector: 'widget1'})@View({ template: ``, bindings: [UpperCasePipe] })export class Widget1{ constructor(public upperCasePipe:UpperCasePipe){ this.upperCasePipe.transform('Un autre exemple...'); }}

Page 71: ChtiJUG - Introduction à Angular2

@Component

@View@Directive

Page 72: ChtiJUG - Introduction à Angular2

@View

@Animation

@Inject

@InjectLazy

@Optional

@Host

@Parent

@Pipe

@Property

@Event

@RouteConfig

@HostBinding

@HostEvent

@ContentChild

@ContentChildren

@ViewChildren

Page 73: ChtiJUG - Introduction à Angular2

Roadmap

Page 74: ChtiJUG - Introduction à Angular2

Pour une migration heureuse...

Page 75: ChtiJUG - Introduction à Angular2

John Papa's

styleguide

Page 76: ChtiJUG - Introduction à Angular2

Autres Règles

1 composant AngularJS par fichier

ECMAScript 2015

Syntaxe Component As

bindToController dans l'API des

directives

Component-First Approach

Utilise le nouveau Router

Création de service via la méthode

service

Page 77: ChtiJUG - Introduction à Angular2
Page 78: ChtiJUG - Introduction à Angular2
Page 79: ChtiJUG - Introduction à Angular2

eslint-plugin-angular

npm install --save-dev eslint eslint-plugin-angular

Implémente le guideline de John Papa

Rules :

Component-First Approach : ng_no_controller

controllerAs : ng_controller_as_*

Page 80: ChtiJUG - Introduction à Angular2

ngUpgrade.jsMixer AngularJS et

Angular2

Page 81: ChtiJUG - Introduction à Angular2

Démo

Page 82: ChtiJUG - Introduction à Angular2

https://github.com/Gillespie59/

angular2-migration-sample

Page 84: ChtiJUG - Introduction à Angular2

Questions ?

Page 85: ChtiJUG - Introduction à Angular2