Angular 2

@EmmanuelDemey

Emmanuel DEMEY

Consultant & Formateur Web

Zenika Nord

       @EmmanuelDemey

Web / Domotique / Histoire / Biérologie

Les choses que nous n'aimons pas...

Architecture AngularJS

DI (provider, service, factory...)

MV*

MV*

MV*

Filtres

API des Directives

app.directive('MyDirective', function(){
    return  {       
       restrict: 'AE',
       require: '?^^ngModel',
       scope: { variable: '@' },  
       compile: function(...) {
           return {
               pre: function(...) { ... },
               post: function(...) { ... }
           }
       },
       link: function(...) { ... }       
    }
});
            
<input ng-model="firstName">

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

2-way data-binding

2-way data-binding

<input ng-model="firstName"
       ng-model-options="options">

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

2-way data-binding

<input ng-model="firstName">

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

Et ce n'est pas fini...

Mais aussi...

  • JavaScript
  • Hiérarchie des scopes
  • Pas de Server-Side Rendering
  • Gestion des événements (ngClick, ...)
  • Gestion des attributs HTML (ngSrc, ...)

La solution... Angular 2

Attention !

Version Beta

P(eu|as) de Doc

Rapidité

Simplicité

Productivité

  • Architecture
  • Composants
  • Injection de Dépendance
  • Pipes

Architecture Angular 2

<app></app>

menu

grid

gallery

DI
(classes ES6 ou TypeScript)
 

Pipes
(classes ES6 ou TypeScript)
 

La Famille JavaScript

ES5

ES2015

TypeScript

  • Classe
  • Modules
  • ...
  • Type Annotation
  • Meta Annotation
  • ...

ES5

ES2016 

TypeScript

Dart

Les Web Components

Custom Elements

Templates

Imports

Shadow DOM

Les composants

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
//<my-app></my-app>
function MyAppComponent() {

}

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

Composant version ES5

import {Component} from 'angular2/core';

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

}

Composant version TypeScript

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

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

}
                
bootstrap(MyAppComponent);
            

Bootstrap de l'Application

Binding

Root Cpt

Child1 Cpt

Child2 Cpt

[property]="expression"

(event)="update()"

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

Property Binding

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

Property Binding

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

Property Binding

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

Property Binding

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

Event Binding

<input (event)="expression" />
  • Accès à tous les événements des éléments HTML
  • Possibilité de définir de nouveaux événements

Event Bindings

//<beer-item [beer]="'Maredsous'" (selectBeer)="sendToBeerTap($event)"></beerItem>
@Component({
  selector: 'beer-item',
  template: `<section>
                <h2>{{beer}}</h2>
                <button (click)="selectItem()">Je veux celle-ci !</button>
            </section>`
})
export class BeerItem {
  @Input() beer: String;
  @Output() selectBeer: EventEmitter<any> = new EventEmitter();
  
  selectItem() {
     this.selectBeer.next(this.beer);
  }
}
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 ?

Syntaxe valide ?

Component Dependency

  • Nécessité d'importer les composants nécessaires à votre application
  • Propriété directives de @Component
  • Erreur si composants non utilisés

Component Dependency

import {BeerItem} from 'BeerItem';

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

Support des WebComponents

Injection de Dépendance

Injection de Dépendances

  • Code métier dans des services
  • Chaque Service est un singleton
  • Principe d'Hollywood
  • Multiples implémentations en NG1 !

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

Injecteur Principal

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

bootstrap(MyAppComponent, [BreweryService]);

Injecteur Principal - useValue

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

bootstrap(MyAppComponent, [provide(String, {useValue: 'Zenika Brewery'})]);

Injecteur Principal - useClass

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

bootstrap(MyAppComponent, [
        provide(BreweryServiceI, {useClass: BreweryService})
]);

Injecteur Principal - useFactory

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

bootstrap(MyAppComponent, [
        provide(String, {
          useFactory: (breweryService:BreweryService) => {
              return breweryService.getBreweryName();  
          },
          deps: [BreweryService]
        })
]

Child Injector

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

bootstrap(MyAppComponent, [provide(String, {useValue: 'Zenika Brewery'})]);

Child Injector

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

Child Injector

@Component({
    selector: 'welcome-message',
    template: `<h1>Welcome to our {{breweryName}}</h1>`,
    providers: [
        provide(String, {useValue: 'Awesome Zenika Brewery'})
    ]
})
export class WelcomeMessage {
    constructor(public breweryName:String){ ... }
}

Pipes

Petit Rappel


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

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, slice, json et date

Pipes

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

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

Pipes

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

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

Pipes

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

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

@Component

@View

@Directive

@Animation

@Inject

@InjectLazy

@Optional

@Host

@Parent

@Pipe

@Property

@Event

@RouteConfig

@HostBinding

@HostEvent

@ContentChildren

@ViewChild

@ViewChildren

@Input

@Output

@Attribute

@CanActivate

 

Roadmap

Questions ?

Made with Slides.com