SlideShare una empresa de Scribd logo
1 de 76
Descargar para leer sin conexión
Exploring Angular 2
Angular 2
The Next Framework
@cef62

github.com/cef62

Senior frontend engineer @ 

Staff member of Frontenders Verona

Italian React & Angular Communities Maintainer
MATTEO RONCHI
AngularJS history
• AngularJS was originally developed in 2009 by Misko
Hevery and Adam Abrons
• Misko Hevery started to work for Google in 2009
• 1st release of AngularJS: 1 developer, 3 weeks, 1000 loc
• AngularJS version 1.0 was released in 2012 by Google
• Angular version 2 was released in September 2016 after
2 years development
WELCOME TO THE FUTURE
Angular 2 features
• Optimized for both desktop and mobile
• Ahead of Time (AoT) compilation
• Incredible performances
• Native Reactive support
ANGULAR 2 BASICS
@INJECTABLE
export class MyService {
getData() {
return this.loadData.load();
}
}
import { Injectable } from `angular2/core`;
@Injectable()
export class MyService {
constructor(private loadData:LoadData) {}
getData() {
return this.loadData.load();
}
}
ANGULAR 2 BASICS
@COMPONENT
import { Component } from '@angular/core';
@Component({
selector: 'hello',
template: '<p>Hello, {{name}}</p>'
})
export class Hello {
name: string;
constructor() {
this.name = 'World';
}
}
ANGULAR 2 BASICS
@DIRECTIVE
import {
Directive, HostListener
} from '@angular/core';
@Directive({
selector: `[confirm]`
})
export class ConfirmDirective {
@HostListener(`click`, [`$event`])
confirmFirst(event: Event) {
return window.confirm(
`Are you sure you want to do this?`
);
}
}
// Usage
<button type="button"
(click)="visitOtherPage()"
confirm>Visit another page</button>
ANGULAR 2 BASICS
@PIPES
import { Component } from '@angular/core';
@Component({
selector: `product-price`,
template: `<p>Price: {{ price | currency }}</p>`
})
export class ProductPrice {
price: number = 99.99;
}
import { Pipe, PipeTransform } from '@angular/core';
const UNITS = ['B', 'KB', 'MB', 'GB'];
@Pipe({
name: 'formatFileSize'
})
export class FormatSize implements PipeTransform {
transform(
bytes: number = 0,
precision: number = 2
) : string {
if (!isFinite(bytes)) return ‘?';
let unit = 0;
while ( bytes >= 1024 ) {
bytes /= 1024;
unit ++;
}
return bytes.toFixed(precision) + ' ' + UNITS[unit];
}
}
ANGULAR 2 BASICS
HTTP SERVICE
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs';
import {Hero} from './hero';
@Injectable()
export class LoadDataService {
constructor(private http: Http) {}
search(term: string): Observable<Hero[]> {
return this.http
.get(`app/heroes/?name=${term}`)
.map((r: Response) => {
return r.json().data as Hero[]
});
}
}
IN THE ZONE
AngularJS $digest cycle
• AngularJS engine is built using a dirty checking algorithm.
• Application state is a single entity connected to every
visual component and calculated every time a
component mutates some data
• It’s very easy to trigger unwanted $digest cycles
impacting performances
• Very difficult to debug
Angular 2 Change Detection engine
• Based on ngZone
• Recalculate the components tree state after every async
interaction (events, timers, observables..)
• Every component has its own Change Detector
• Component’s Change Detector is generated at runtime
to improve performances
• Developers can control how and when components are
recalculated
– ngBook2
“When one of the components change, no
matter where in the tree it is, a change
detection pass is triggered for the whole tree,
from top to bottom.”
CD
CD CD
CD CDCD
CD CD
CHANGE DETECTION
TRAVELS TOP TO BOTTOM
ChangeDetection
Flow
CHANGE DETECTION IS DEFINED AT
COMPONENT LEVEL
• Every component gets a change detector responsible
for checking the bindings defined in its template
• ChangeDetectionStrategy
• default: update the component every time data
changes
• onPush: update the component only when its
inputs change or the component requests to be
updated
CHANGE DETECTION (onPush)
WITH IMMUTABLE DATA
CD
CD
CD CD
CD CD
ChangeDetection
Flow
CHANGE DETECTION (onPush)
WITH OBSERVABLES
CD
CD
CD
CD
ChangeDetection
Flow
TYPESCRIPT: A FIRST CLASS CITIZEN
Why typescript
• Angular2 Dependency Injection system is based on
type reflection
• Annotations offer a powerful and very expressive way to
describe elements
Pros
• Improve Developer Experience with better tools
• Compile time error check
• Type safety
• Better documentation
• Easy to adopt for backend developers
Cons
• Increase project’s technical debt
• Slower learning curve for traditional javascript developer
• Impossible to remove without a complete rewrite
THINKING COMPONENTS
Modern web is all about components
• Thinking of components instead of views improves
decoupling and separation of concerns
• Components are composable and highly reusable
• Easier to test
• UX and UI teams integrate better
A component is
• exported as a custom HTML tag: <tab-bar />
• defined by an HTML template
• enhanced using the @component decorator
• controlled using its inputs and outputs
• initialized by Angular Dependency Injection engine
SELECTOR
@COMPONENT
import { Component } from '@angular/core';
@Component({
selector: 'hello',
template: '<p>Hello, {{name}}</p>'
})
export class Hello {
name: string;
constructor() {
this.name = 'World';
}
}
selector is the element property that we use to tell
Angular to create and insert an instance of this
component.
COMPONENT TEMPLATE
@COMPONENT
template is an HTML string that tells Angular what
needs to be to rendered in the DOM.
templateUrl is a relative path to a file containing the
component HTML string.
TEMPLATE SYNTAX
• template tags {{ expression }}: Execute arbitrary
expressions. Eg: {{1+1}.
• property binding [key]=“value”. Used to pass data to a
component.
• event binding (event)=“expression”. Expression
executed anytime the registered event fires.
• 2-way binding <input [(ngModel)]=“u.name"> Requires
to import `FormsModule` to be used.
INPUTS
@COMPONENT
import {Component, Input} from `@angular/
core`;
@Component({
selector: `hello`,
template: `<p>Hello, {{name}}</p>`
})
export class Hello {
@Input() name: string;
}
import { Component } from `@angular/core`;
@Component({
selector: `hello`,
inputs: [`name`],
template: `<p>Hello, {{name}}</p>`
})
export class Hello {}
// To bind to a raw string
<hello name="World"></hello>
// To bind to a variable in the parent scope
<hello [name]="userName"></hello>
OUTPUTS
@COMPONENT
import {Component} from `@angular/core`;
@Component({
selector: `counter`,
template: `
<div>
<p>Count: {{ num }}</p>
<button (click)="increment()">Increment</button>
</div>
`
})
export class Counter {
num: number = 0;
increment() {
this.num++;
}
}
import {
Component, EventEmitter, Output
} from `@angular/core`;
@Component({
selector: `counter`,
template: `
<div>
<p>Count: {{ count }}</p>
<button (click)="increment()">Increment</button>
</div>
`
})
export class Counter {
count: number = 0;
@Output() result: EventEmitter = new EventEmitter();
increment() {
this.result.emit(this.count);
}
}
CHILD COMPONENTS
@COMPONENT
import {Component, ViewChild} from `@angular/
core`;
import {Alert} from `./alert.component`;
@Component({
selector: `app`,
template: `
<my-alert>My alert</my-alert>
<button (click)="showAlert()">Show Alert</
button>`
})
export class App {
@ViewChild(Alert) alert: Alert;
showAlert() {
this.alert.show();
}
}
import {Component, ViewChild} from `@angular/core`;
import {Alert} from `./alert.component`;
@Component({
selector: `app`,
template: `
<my-alert>My alert</my-alert>
<input #msg type=“text” />
<button (click)="showAlert()">Show Alert</button>`
})
export class App {
@ViewChild(Alert) alert: Alert;
@ViewChild(`msg`) msgInput;
showAlert() {
const txt = this.msgInput.nativeElement.value;
this.alert.show(txt);
}
}
CONTENT TRANSCLUSION
@COMPONENT
import {Component, Input} from `@angular/core`;
@Component({
selector: `hello`,
template: `<div>
<p>Hello, {{name}}</p>
<ng-content><p>No extra data</p></ng-content>
</div>`
})
export class Hello {
@Input() name: string;
}
// Usage
<hello name=“Matteo”>
<div>
<h1>Some other data</h1>
<p>Some text</p>
</div>
</hello>
COMPONENT LIFECYCLE
Components & Directives shared lifecycle
ngOnChanges input property value changes
ngOnInit Initialization step
ngDoCheck every change detection cycle
ngOnDestroy before destruction
import {
Component, OnInit
} from '@angular/core';
@Component({
selector: 'hello',
template: '<p>Hello, {{name}}</p>'
})
export class Hello implements OnInit {
name: string;
constructor() {
this.name = 'World';
}
ngOnInit() {
// do something to initialize the component
}
}
import {
Directive, OnInit, OnDestroy
} from '@angular/core';
@Directive({
selector: `[mySpy]`
})
export class SpyDirective implements OnInit, OnDestroy {
constructor(private logger: LoggerService) { }
ngOnInit() {
this.logIt(`onInit`);
}
ngOnDestroy() {
this.logIt(`onDestroy`);
}
private logIt(msg: string) {
this.logger.log(`Spy ${msg}`);
}
}
// Usage
<div mySpy>...</div>
–Angular official docs
“Angular only calls a directive/component hook
method if it is defined.”
COMPONENT STYLE
INLINE STYLES
import { Component } from '@angular/core';
const baseStyle = {
backgroundColor: 'green',
padding: '10px'
};
@Component({
selector: 'hello',
template: ‘<p [ngStyle]="style">Hello!</p>'
})
export class Hello {
style: any = baseStyle;
}
COMPONENT STYLE
VIEW ENCAPSULATION
• Emulated (default) - styles from main HTML propagate to the
component. Styles defined in this component's @Component
decorator are scoped to this component only.
• Native (shadow DOM)- styles from main HTML do not
propagate to the component. Styles defined in this component's
@Component decorator are scoped to this component only.
• None - styles from the component propagate back to the main
HTML and therefore are visible to all components on the page.
———
Be careful with apps that have None and Native components mixed
in the application. All components with None encapsulation will
have their styles duplicated in all components with Native
encapsulation.
import {
Component, ViewEncapsulation
} from '@angular/core';
@Component({
selector: ‘hello',
styles: [`
.main {
background-color: green;
padding: 10px;
}
`],
encapsulation: ViewEncapsulation.Emulated,
template: `<p class="main">Hello!</p>`
})
export class Hello {}
// OUTPUT HTML
<p class="main"
_ngcontent-yok-5=""
>Hello!</p>
// output css (inside <head>)
.main[_ngcontent-yok-5] {
background-color: green;
padding: 10px;
}
BE REACTIVE!
OBSERVE ALL THE THINGS!
–Angular official docs
“Observables open up a continuous channel of
communication in which multiple values of data
can be emitted over time […] Angular 2 uses
observables extensively - you'll see them in the
HTTP service and the event system…”
–A. Staltz
“A stream is a sequence of ongoing events
ordered in time. It can emit 3 different things: a
value, an error, or a "completed" signal.
Consider that the "completed" takes place, for
instance, when the current window is closed.”
OBSERVABLES vs PROMISES
• Both provide us with abstractions that help us deal
with the asynchronous nature of our applications.
• Observables are cancellable.
• Observables can be retried using one of the retry
operators provided by the API, such as retry and
retryWhen.
• Promises require the caller to have access to the
original function that returned the promise in order
to have a retry capability.
import { Observable } from ‘rxjs/Observable';
const dataStream = new Observable((observer) => {
setTimeout(() => {
observer.next(42);
}, 1000);
setTimeout(() => {
observer.next(43);
}, 2000);
setTimeout(() => {
observer.complete();
}, 3000);
});
const subscription = dataStream.subscribe(
(value) => this.values.push(value),
(error) => this.anyErrors = true,
() => this.finished = true
);
import { Component, OnInit, ViewChild } from `@angular/core`;
import { Observable } from 'rxjs';
@Component({
selector: `app`,
template: `<input type="text" #username />`
})
export class App implements OnInit {
@ViewChild(`username`) username: any;
ngOnInit(): void {
Observable
.fromEvent(this.username.nativeElement, 'keyup')
.map((e: any) => e.target.value)
.filter((text: string) => text.length > 5)
.debounceTime(1000)
.subscribe((text: string) => this.submit(text));
}
submit(text: string): void {
console.log('submitted: ', text);
}
}
Bootstrapping Angular
Bootstrapping is an essential process in Angular - it is
where the application is loaded when Angular comes to
life.
Bootstrapping Angular 2 applications is certainly
different from Angular 1.x, but is still a straightforward
procedure.
// app.modules.ts
import { BrowserModule } from '@angular/platform-
browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './[PATH]/app.component';
import { MyComponent } from ‘./[PATH]/some.component';
import { SomeService } from “./[PATH]/some.service";
@NgModule({
declarations: [AppComponent, MyComponent],
providers: [SomeService],
imports: [BrowserModule, HttpModule],
bootstrap: [AppComponent]
})
class AppModule {}
// main.ts
import { platformBrowserDynamic } from '@angular/
platform-browser-dynamic';
import { AppModule } from './app/';
// Bootstrap main component
platformBrowserDynamic().bootstrapModule(AppModule);
angular-cli
FAST PROJECT SETUP

WORKING EXAMPLE: github.com/commit-university/exploring-angular-2
THANKS!
@CEF62

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshop
 
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Building Universal Applications with Angular 2
Building Universal Applications with Angular 2
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core concepts
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Angular 2 Crash Course
Angular  2 Crash CourseAngular  2 Crash Course
Angular 2 Crash Course
 
2 years of angular: lessons learned
2 years of angular: lessons learned2 years of angular: lessons learned
2 years of angular: lessons learned
 
Async patterns in javascript
Async patterns in javascriptAsync patterns in javascript
Async patterns in javascript
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
 
Angular 5
Angular 5Angular 5
Angular 5
 
Angular2 - In Action
Angular2  - In ActionAngular2  - In Action
Angular2 - In Action
 
AngularJS2 / TypeScript / CLI
AngularJS2 / TypeScript / CLIAngularJS2 / TypeScript / CLI
AngularJS2 / TypeScript / CLI
 
Angular 2 - Better or worse
Angular 2 - Better or worseAngular 2 - Better or worse
Angular 2 - Better or worse
 
Angular2
Angular2Angular2
Angular2
 

Destacado

Destacado (18)

(Have a) rest with Laravel
(Have a) rest with Laravel(Have a) rest with Laravel
(Have a) rest with Laravel
 
Commit University - Microsoft Azure
Commit University - Microsoft AzureCommit University - Microsoft Azure
Commit University - Microsoft Azure
 
Getting Started with Angular 2
Getting Started with Angular 2Getting Started with Angular 2
Getting Started with Angular 2
 
Windows Azure Platform
Windows Azure PlatformWindows Azure Platform
Windows Azure Platform
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Angular 2.0
Angular 2.0Angular 2.0
Angular 2.0
 
Angular 2 a traveler's diary
Angular 2   a traveler's diaryAngular 2   a traveler's diary
Angular 2 a traveler's diary
 
Brief intro 2 to angular 2
Brief intro 2 to angular 2Brief intro 2 to angular 2
Brief intro 2 to angular 2
 
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
AzovDevMeetup 2016 | Angular 2: обзор | Александр ШевнинAzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
 
PPT on Angular 2 Development Tutorial
PPT on Angular 2 Development TutorialPPT on Angular 2 Development Tutorial
PPT on Angular 2 Development Tutorial
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
 
Angular 2 with typescript
Angular 2 with typescriptAngular 2 with typescript
Angular 2 with typescript
 
Get that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and ElectronGet that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and Electron
 
An afternoon with angular 2
An afternoon with angular 2An afternoon with angular 2
An afternoon with angular 2
 
Angular 2
Angular 2Angular 2
Angular 2
 
The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Silverlight
SilverlightSilverlight
Silverlight
 

Similar a Commit University - Exploring Angular 2

Similar a Commit University - Exploring Angular 2 (20)

Introduction to Angular2
Introduction to Angular2Introduction to Angular2
Introduction to Angular2
 
Angular 2 - a New Hope
Angular 2 - a New HopeAngular 2 - a New Hope
Angular 2 - a New Hope
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
mean stack
mean stackmean stack
mean stack
 
Meetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son applicationMeetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son application
 
Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6
 
Angular 2 in-1
Angular 2 in-1 Angular 2 in-1
Angular 2 in-1
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Technozaure - Angular2
Technozaure - Angular2Technozaure - Angular2
Technozaure - Angular2
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core Concepts
 
Angular IO
Angular IOAngular IO
Angular IO
 
Peggy angular 2 in meteor
Peggy   angular 2 in meteorPeggy   angular 2 in meteor
Peggy angular 2 in meteor
 
Angular 2.0 - What to expect
Angular 2.0 - What to expectAngular 2.0 - What to expect
Angular 2.0 - What to expect
 
Angular 2
Angular 2Angular 2
Angular 2
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdf
 

Más de Commit University

Más de Commit University (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Breaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdf
Breaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdfBreaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdf
Breaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdf
 
Accelerating API Development: A Pit Stop with Gin-Gonic in Golang-Slide.pdf
Accelerating API Development: A Pit Stop with Gin-Gonic in Golang-Slide.pdfAccelerating API Development: A Pit Stop with Gin-Gonic in Golang-Slide.pdf
Accelerating API Development: A Pit Stop with Gin-Gonic in Golang-Slide.pdf
 
Slide-10years.pdf
Slide-10years.pdfSlide-10years.pdf
Slide-10years.pdf
 
Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...
Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...
Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...
 
Vue.js slots.pdf
Vue.js slots.pdfVue.js slots.pdf
Vue.js slots.pdf
 
Commit - Qwik il framework che ti stupirà.pptx
Commit - Qwik il framework che ti stupirà.pptxCommit - Qwik il framework che ti stupirà.pptx
Commit - Qwik il framework che ti stupirà.pptx
 
Sviluppare da zero una Angular Web App per la PA
Sviluppare da zero una Angular Web App per la PASviluppare da zero una Angular Web App per la PA
Sviluppare da zero una Angular Web App per la PA
 
Backstage l'Internal Developer Portal Open Source per una migliore Developer ...
Backstage l'Internal Developer Portal Open Source per una migliore Developer ...Backstage l'Internal Developer Portal Open Source per una migliore Developer ...
Backstage l'Internal Developer Portal Open Source per una migliore Developer ...
 
Prisma the ORM that node was waiting for
Prisma the ORM that node was waiting forPrisma the ORM that node was waiting for
Prisma the ORM that node was waiting for
 
Decision-making for Software Development Teams - Commit University
Decision-making for Software Development Teams - Commit UniversityDecision-making for Software Development Teams - Commit University
Decision-making for Software Development Teams - Commit University
 
Component Design Pattern nei Game Engine.pdf
Component Design Pattern nei Game Engine.pdfComponent Design Pattern nei Game Engine.pdf
Component Design Pattern nei Game Engine.pdf
 
Un viaggio alla scoperta dei Language Models e dell’intelligenza artificiale ...
Un viaggio alla scoperta dei Language Models e dell’intelligenza artificiale ...Un viaggio alla scoperta dei Language Models e dell’intelligenza artificiale ...
Un viaggio alla scoperta dei Language Models e dell’intelligenza artificiale ...
 
Prototipazione Low-Code con AWS Step Functions
Prototipazione Low-Code con AWS Step FunctionsPrototipazione Low-Code con AWS Step Functions
Prototipazione Low-Code con AWS Step Functions
 
KMM survival guide: how to tackle struggles between Kotlin and Swift
KMM survival guide: how to tackle struggles between Kotlin and SwiftKMM survival guide: how to tackle struggles between Kotlin and Swift
KMM survival guide: how to tackle struggles between Kotlin and Swift
 
Da Vuex a Pinia: come fare la migrazione
Da Vuex a Pinia: come fare la migrazioneDa Vuex a Pinia: come fare la migrazione
Da Vuex a Pinia: come fare la migrazione
 
Orchestrare Micro-frontend con micro-lc
Orchestrare Micro-frontend con micro-lcOrchestrare Micro-frontend con micro-lc
Orchestrare Micro-frontend con micro-lc
 
Fastify has defeated Lagacy-Code
Fastify has defeated Lagacy-CodeFastify has defeated Lagacy-Code
Fastify has defeated Lagacy-Code
 
SwiftUI vs UIKit
SwiftUI vs UIKitSwiftUI vs UIKit
SwiftUI vs UIKit
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Commit University - Exploring Angular 2

  • 2. Angular 2 The Next Framework
  • 3. @cef62 github.com/cef62 Senior frontend engineer @ Staff member of Frontenders Verona Italian React & Angular Communities Maintainer MATTEO RONCHI
  • 4. AngularJS history • AngularJS was originally developed in 2009 by Misko Hevery and Adam Abrons • Misko Hevery started to work for Google in 2009 • 1st release of AngularJS: 1 developer, 3 weeks, 1000 loc • AngularJS version 1.0 was released in 2012 by Google • Angular version 2 was released in September 2016 after 2 years development
  • 5. WELCOME TO THE FUTURE
  • 6. Angular 2 features • Optimized for both desktop and mobile • Ahead of Time (AoT) compilation • Incredible performances • Native Reactive support
  • 8. export class MyService { getData() { return this.loadData.load(); } }
  • 9. import { Injectable } from `angular2/core`; @Injectable() export class MyService { constructor(private loadData:LoadData) {} getData() { return this.loadData.load(); } }
  • 11. import { Component } from '@angular/core'; @Component({ selector: 'hello', template: '<p>Hello, {{name}}</p>' }) export class Hello { name: string; constructor() { this.name = 'World'; } }
  • 13. import { Directive, HostListener } from '@angular/core'; @Directive({ selector: `[confirm]` }) export class ConfirmDirective { @HostListener(`click`, [`$event`]) confirmFirst(event: Event) { return window.confirm( `Are you sure you want to do this?` ); } } // Usage <button type="button" (click)="visitOtherPage()" confirm>Visit another page</button>
  • 15. import { Component } from '@angular/core'; @Component({ selector: `product-price`, template: `<p>Price: {{ price | currency }}</p>` }) export class ProductPrice { price: number = 99.99; }
  • 16. import { Pipe, PipeTransform } from '@angular/core'; const UNITS = ['B', 'KB', 'MB', 'GB']; @Pipe({ name: 'formatFileSize' }) export class FormatSize implements PipeTransform { transform( bytes: number = 0, precision: number = 2 ) : string { if (!isFinite(bytes)) return ‘?'; let unit = 0; while ( bytes >= 1024 ) { bytes /= 1024; unit ++; } return bytes.toFixed(precision) + ' ' + UNITS[unit]; } }
  • 18. import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import {Observable} from 'rxjs'; import {Hero} from './hero'; @Injectable() export class LoadDataService { constructor(private http: Http) {} search(term: string): Observable<Hero[]> { return this.http .get(`app/heroes/?name=${term}`) .map((r: Response) => { return r.json().data as Hero[] }); } }
  • 20. AngularJS $digest cycle • AngularJS engine is built using a dirty checking algorithm. • Application state is a single entity connected to every visual component and calculated every time a component mutates some data • It’s very easy to trigger unwanted $digest cycles impacting performances • Very difficult to debug
  • 21. Angular 2 Change Detection engine • Based on ngZone • Recalculate the components tree state after every async interaction (events, timers, observables..) • Every component has its own Change Detector • Component’s Change Detector is generated at runtime to improve performances • Developers can control how and when components are recalculated
  • 22. – ngBook2 “When one of the components change, no matter where in the tree it is, a change detection pass is triggered for the whole tree, from top to bottom.”
  • 23. CD CD CD CD CDCD CD CD CHANGE DETECTION TRAVELS TOP TO BOTTOM ChangeDetection Flow
  • 24. CHANGE DETECTION IS DEFINED AT COMPONENT LEVEL
  • 25. • Every component gets a change detector responsible for checking the bindings defined in its template • ChangeDetectionStrategy • default: update the component every time data changes • onPush: update the component only when its inputs change or the component requests to be updated
  • 26. CHANGE DETECTION (onPush) WITH IMMUTABLE DATA CD CD CD CD CD CD ChangeDetection Flow
  • 27. CHANGE DETECTION (onPush) WITH OBSERVABLES CD CD CD CD ChangeDetection Flow
  • 28. TYPESCRIPT: A FIRST CLASS CITIZEN
  • 29. Why typescript • Angular2 Dependency Injection system is based on type reflection • Annotations offer a powerful and very expressive way to describe elements
  • 30. Pros • Improve Developer Experience with better tools • Compile time error check • Type safety • Better documentation • Easy to adopt for backend developers
  • 31. Cons • Increase project’s technical debt • Slower learning curve for traditional javascript developer • Impossible to remove without a complete rewrite
  • 33. Modern web is all about components • Thinking of components instead of views improves decoupling and separation of concerns • Components are composable and highly reusable • Easier to test • UX and UI teams integrate better
  • 34. A component is • exported as a custom HTML tag: <tab-bar /> • defined by an HTML template • enhanced using the @component decorator • controlled using its inputs and outputs • initialized by Angular Dependency Injection engine
  • 36. import { Component } from '@angular/core'; @Component({ selector: 'hello', template: '<p>Hello, {{name}}</p>' }) export class Hello { name: string; constructor() { this.name = 'World'; } }
  • 37. selector is the element property that we use to tell Angular to create and insert an instance of this component.
  • 39. template is an HTML string that tells Angular what needs to be to rendered in the DOM. templateUrl is a relative path to a file containing the component HTML string.
  • 40. TEMPLATE SYNTAX • template tags {{ expression }}: Execute arbitrary expressions. Eg: {{1+1}. • property binding [key]=“value”. Used to pass data to a component. • event binding (event)=“expression”. Expression executed anytime the registered event fires. • 2-way binding <input [(ngModel)]=“u.name"> Requires to import `FormsModule` to be used.
  • 42. import {Component, Input} from `@angular/ core`; @Component({ selector: `hello`, template: `<p>Hello, {{name}}</p>` }) export class Hello { @Input() name: string; }
  • 43. import { Component } from `@angular/core`; @Component({ selector: `hello`, inputs: [`name`], template: `<p>Hello, {{name}}</p>` }) export class Hello {}
  • 44. // To bind to a raw string <hello name="World"></hello> // To bind to a variable in the parent scope <hello [name]="userName"></hello>
  • 46. import {Component} from `@angular/core`; @Component({ selector: `counter`, template: ` <div> <p>Count: {{ num }}</p> <button (click)="increment()">Increment</button> </div> ` }) export class Counter { num: number = 0; increment() { this.num++; } }
  • 47. import { Component, EventEmitter, Output } from `@angular/core`; @Component({ selector: `counter`, template: ` <div> <p>Count: {{ count }}</p> <button (click)="increment()">Increment</button> </div> ` }) export class Counter { count: number = 0; @Output() result: EventEmitter = new EventEmitter(); increment() { this.result.emit(this.count); } }
  • 49. import {Component, ViewChild} from `@angular/ core`; import {Alert} from `./alert.component`; @Component({ selector: `app`, template: ` <my-alert>My alert</my-alert> <button (click)="showAlert()">Show Alert</ button>` }) export class App { @ViewChild(Alert) alert: Alert; showAlert() { this.alert.show(); } }
  • 50. import {Component, ViewChild} from `@angular/core`; import {Alert} from `./alert.component`; @Component({ selector: `app`, template: ` <my-alert>My alert</my-alert> <input #msg type=“text” /> <button (click)="showAlert()">Show Alert</button>` }) export class App { @ViewChild(Alert) alert: Alert; @ViewChild(`msg`) msgInput; showAlert() { const txt = this.msgInput.nativeElement.value; this.alert.show(txt); } }
  • 52. import {Component, Input} from `@angular/core`; @Component({ selector: `hello`, template: `<div> <p>Hello, {{name}}</p> <ng-content><p>No extra data</p></ng-content> </div>` }) export class Hello { @Input() name: string; } // Usage <hello name=“Matteo”> <div> <h1>Some other data</h1> <p>Some text</p> </div> </hello>
  • 54. Components & Directives shared lifecycle ngOnChanges input property value changes ngOnInit Initialization step ngDoCheck every change detection cycle ngOnDestroy before destruction
  • 55. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'hello', template: '<p>Hello, {{name}}</p>' }) export class Hello implements OnInit { name: string; constructor() { this.name = 'World'; } ngOnInit() { // do something to initialize the component } }
  • 56. import { Directive, OnInit, OnDestroy } from '@angular/core'; @Directive({ selector: `[mySpy]` }) export class SpyDirective implements OnInit, OnDestroy { constructor(private logger: LoggerService) { } ngOnInit() { this.logIt(`onInit`); } ngOnDestroy() { this.logIt(`onDestroy`); } private logIt(msg: string) { this.logger.log(`Spy ${msg}`); } } // Usage <div mySpy>...</div>
  • 57. –Angular official docs “Angular only calls a directive/component hook method if it is defined.”
  • 59. import { Component } from '@angular/core'; const baseStyle = { backgroundColor: 'green', padding: '10px' }; @Component({ selector: 'hello', template: ‘<p [ngStyle]="style">Hello!</p>' }) export class Hello { style: any = baseStyle; }
  • 61. • Emulated (default) - styles from main HTML propagate to the component. Styles defined in this component's @Component decorator are scoped to this component only. • Native (shadow DOM)- styles from main HTML do not propagate to the component. Styles defined in this component's @Component decorator are scoped to this component only. • None - styles from the component propagate back to the main HTML and therefore are visible to all components on the page. ——— Be careful with apps that have None and Native components mixed in the application. All components with None encapsulation will have their styles duplicated in all components with Native encapsulation.
  • 62. import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: ‘hello', styles: [` .main { background-color: green; padding: 10px; } `], encapsulation: ViewEncapsulation.Emulated, template: `<p class="main">Hello!</p>` }) export class Hello {}
  • 63. // OUTPUT HTML <p class="main" _ngcontent-yok-5="" >Hello!</p> // output css (inside <head>) .main[_ngcontent-yok-5] { background-color: green; padding: 10px; }
  • 65. –Angular official docs “Observables open up a continuous channel of communication in which multiple values of data can be emitted over time […] Angular 2 uses observables extensively - you'll see them in the HTTP service and the event system…”
  • 66. –A. Staltz “A stream is a sequence of ongoing events ordered in time. It can emit 3 different things: a value, an error, or a "completed" signal. Consider that the "completed" takes place, for instance, when the current window is closed.”
  • 68. • Both provide us with abstractions that help us deal with the asynchronous nature of our applications. • Observables are cancellable. • Observables can be retried using one of the retry operators provided by the API, such as retry and retryWhen. • Promises require the caller to have access to the original function that returned the promise in order to have a retry capability.
  • 69. import { Observable } from ‘rxjs/Observable'; const dataStream = new Observable((observer) => { setTimeout(() => { observer.next(42); }, 1000); setTimeout(() => { observer.next(43); }, 2000); setTimeout(() => { observer.complete(); }, 3000); }); const subscription = dataStream.subscribe( (value) => this.values.push(value), (error) => this.anyErrors = true, () => this.finished = true );
  • 70. import { Component, OnInit, ViewChild } from `@angular/core`; import { Observable } from 'rxjs'; @Component({ selector: `app`, template: `<input type="text" #username />` }) export class App implements OnInit { @ViewChild(`username`) username: any; ngOnInit(): void { Observable .fromEvent(this.username.nativeElement, 'keyup') .map((e: any) => e.target.value) .filter((text: string) => text.length > 5) .debounceTime(1000) .subscribe((text: string) => this.submit(text)); } submit(text: string): void { console.log('submitted: ', text); } }
  • 72. Bootstrapping is an essential process in Angular - it is where the application is loaded when Angular comes to life. Bootstrapping Angular 2 applications is certainly different from Angular 1.x, but is still a straightforward procedure.
  • 73. // app.modules.ts import { BrowserModule } from '@angular/platform- browser'; import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { AppComponent } from './[PATH]/app.component'; import { MyComponent } from ‘./[PATH]/some.component'; import { SomeService } from “./[PATH]/some.service"; @NgModule({ declarations: [AppComponent, MyComponent], providers: [SomeService], imports: [BrowserModule, HttpModule], bootstrap: [AppComponent] }) class AppModule {}
  • 74. // main.ts import { platformBrowserDynamic } from '@angular/ platform-browser-dynamic'; import { AppModule } from './app/'; // Bootstrap main component platformBrowserDynamic().bootstrapModule(AppModule);
  • 75. angular-cli FAST PROJECT SETUP WORKING EXAMPLE: github.com/commit-university/exploring-angular-2