SlideShare a Scribd company logo
Angular 2
@EmmanuelDemey
Emmanuel
DEMEY
Consultant & Formateur Web
Zenika Nord
@EmmanuelDemey
Web / Domotique / Histoire / Biérologie
ChtiJUG - Introduction à Angular2
Les choses que nous n'aimons pas...
Architecture AngularJS
MV* MV* MV*
Architecture AngularJS
MV* MV* MV*
Architecture AngularJS
DI (provider, service, factory...)
MV* MV* MV*
Architecture AngularJS
DI (provider, service, factory...)
MV* MV* MV*
Filtres
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(...) { ... }
}
});
app.directive('MyDirective', function(){
return {
restrict: 'AE',
require: '?^^ngModel',
scope: { variable: '@' },
compile: function(...) {
return {
pre: function(...) { ... },
post: function(...) { ... }
}
},
link: function(...) { ... }
}
});
API des Directives
app.directive('MyDirective', function(){
return {
restrict: 'AE',
require: '?^^ngModel',
scope: { variable: '@' },
compile: function(...) {
return {
pre: function(...) { ... },
post: function(...) { ... }
}
},
link: function(...) { ... }
}
});
API des Directives
app.directive('MyDirective', function(){
return {
restrict: 'AE',
require: '?^^ngModel',
scope: { variable: '@' },
compile: function(...) {
return {
pre: function(...) { ... },
post: function(...) { ... }
}
},
link: function(...) { ... }
}
});
API des Directives
<input ng-model="firstName">
<p>
{{firstName }}
</p>
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>
2-way data-binding
Et ce n'est pas fini...
Mais aussi...
Pas de Server-Side Rendering
Gestion des événements (ngClick, ...)
Gestion des attributs HTML (ngSrc, ...)
La solution... Angular 2
Attention !
Version Alpha
P(eu|as) de Doc
Architecture
Composants
Injection de Dépendance
Pipes
Architecture Angular 2
<app></app>
Architecture Angular 2
<app></app>
menu grid
gallery
Architecture Angular 2
<app></app>
menu grid
gallery
DI
(classes ES6 ou TypeScript)
Pipes
(classes ES6 ou TypeScript)
La Famille JavaScript
La Famille JavaScript
ES5
La Famille JavaScript
ES5
ES2015
La Famille JavaScript
ES5
ES2015
La Famille JavaScript
ES5
ES2015
TypeScript
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'
}),
new angular.ViewAnnotation({
template: "<main>" +
"<h1> This is my first Angular2 app</h1>" +
"</main>"
})
];
Composant version ES5
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
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
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
//<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;
}
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
//<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);
}
}
Syntaxe valide ?
“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 @View
Erreur si composants non utilisés
Component Dependency
import {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() { ... }
}
ChtiJUG - Introduction à Angular2
Support des
WebComponents
WebComponents
@Component({ })
@View({
template: string,
templateUrl: string,
encapsulation?: ViewEncapsulation,
directives?: List<any>,
styles?: List<string>,
styleUrls?: List<string>,
})
class BeerItem { }
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
}
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 !
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);
}
});
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 - 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')]);
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)]);
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]);
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])]);
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')]);
Child Injector
@Component({
selector: 'welcome-message'
})
@View({
template: `<h1>Welcome to our {{breweryName}}</h1>`
})
class WelcomeMessage {
constructeur(public breweryName:String) { ... }
}
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){ ... }
}
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, limitTo, json et date
Pipes
import {Pipe, PipeTransform} from 'angular2/angular2';
@Pipe({
name: 'UpperCasePipe'
})
export class UpperCasePipe implements PipeTransform {
transform(value: String, args: any[]) {
return value.toUpperCase();
}
}
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{}
Pipes
import {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...');
}
}
@Component
@View@Directive
@View
@Animation
@Inject
@InjectLazy
@Optional
@Host
@Parent
@Pipe
@Property
@Event
@RouteConfig
@HostBinding
@HostEvent
@ContentChild
@ContentChildren
@ViewChildren
Roadmap
Pour une migration heureuse...
John Papa's
styleguide
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
ChtiJUG - Introduction à Angular2
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_*
ngUpgrade.js
Mixer AngularJS et
Angular2
Démo
https://github.com/Gillespie59/
angular2-migration-sample
Repository Github
Documentation
http://blog.thoughtram.io/
NG Europe 2014
NG Conf 2015
AngularU
ESLint Plugin Angular
John Papa Styleguide
Questions ?
ChtiJUG - Introduction à Angular2

More Related Content

What's hot (19)

PDF
Commit University - Exploring Angular 2
Commit University
 
ODP
Angular js-crash-course
Keith Bloomfield
 
PDF
Sharper Better Faster Dagger ‡ - Droidcon SF
Pierre-Yves Ricau
 
PDF
Angular server side rendering - Strategies & Technics
Eliran Eliassy
 
PDF
Angular 2 - The Next Framework
Commit University
 
PDF
Styling recipes for Angular components
Nir Kaufman
 
PDF
Ngrx meta reducers
Eliran Eliassy
 
PDF
ParisJS #10 : RequireJS
Julien Cabanès
 
PDF
Solid angular
Nir Kaufman
 
ODP
AngularJs Crash Course
Keith Bloomfield
 
PPTX
Angular 2.0 Dependency injection
Eyal Vardi
 
PDF
Explaination of angular
Kan-Han (John) Lu
 
PDF
Angular 2: core concepts
Codemotion
 
PDF
An introduction to Angular2
Apptension
 
PDF
AngularJS Project Setup step-by- step guide - RapidValue Solutions
RapidValue
 
PPT
Angular 8
Sunil OS
 
PPTX
Peggy angular 2 in meteor
LearningTech
 
PPTX
Angular js
Behind D Walls
 
PDF
A gently introduction to AngularJS
Gregor Woiwode
 
Commit University - Exploring Angular 2
Commit University
 
Angular js-crash-course
Keith Bloomfield
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Pierre-Yves Ricau
 
Angular server side rendering - Strategies & Technics
Eliran Eliassy
 
Angular 2 - The Next Framework
Commit University
 
Styling recipes for Angular components
Nir Kaufman
 
Ngrx meta reducers
Eliran Eliassy
 
ParisJS #10 : RequireJS
Julien Cabanès
 
Solid angular
Nir Kaufman
 
AngularJs Crash Course
Keith Bloomfield
 
Angular 2.0 Dependency injection
Eyal Vardi
 
Explaination of angular
Kan-Han (John) Lu
 
Angular 2: core concepts
Codemotion
 
An introduction to Angular2
Apptension
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
RapidValue
 
Angular 8
Sunil OS
 
Peggy angular 2 in meteor
LearningTech
 
Angular js
Behind D Walls
 
A gently introduction to AngularJS
Gregor Woiwode
 

Recently uploaded (20)

PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Digital Circuits, important subject in CS
contactparinay1
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Ad

ChtiJUG - Introduction à Angular2