SlideShare a Scribd company logo
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

More Related Content

PDF
Angular 2 - The Next Framework
Commit University
 
PDF
Exploring Angular 2 - Episode 2
Ahmed Moawad
 
PDF
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
PPTX
Angular2 + rxjs
Christoffer Noring
 
PDF
Introduction to Angular 2
Naveen Pete
 
PDF
The productive developer guide to Angular 2
Maurice De Beijer [MVP]
 
PDF
Exploring Angular 2 - Episode 1
Ahmed Moawad
 
PPTX
Migrating an application from Angular 1 to Angular 2
Ross Dederer
 
Angular 2 - The Next Framework
Commit University
 
Exploring Angular 2 - Episode 2
Ahmed Moawad
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
Angular2 + rxjs
Christoffer Noring
 
Introduction to Angular 2
Naveen Pete
 
The productive developer guide to Angular 2
Maurice De Beijer [MVP]
 
Exploring Angular 2 - Episode 1
Ahmed Moawad
 
Migrating an application from Angular 1 to Angular 2
Ross Dederer
 

What's hot (20)

PDF
An introduction to Angular2
Apptension
 
ODP
Introduction to Angular 2
Knoldus Inc.
 
PDF
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Codemotion
 
PDF
Angular2 workshop
Nir Kaufman
 
PDF
Building Universal Applications with Angular 2
Minko Gechev
 
PPTX
Angular js 2
Ran Wahle
 
PDF
Angular2 with TypeScript
Rohit Bishnoi
 
PDF
Angular 2 Essential Training
Patrick Schroeder
 
PDF
Angular 2: core concepts
Codemotion
 
PPTX
Angular2 for Beginners
Oswald Campesato
 
PDF
Angular Dependency Injection
Nir Kaufman
 
PDF
Angular 2 Crash Course
Elisha Kramer
 
PPTX
2 years of angular: lessons learned
Dirk Luijk
 
PPTX
Async patterns in javascript
Ran Wahle
 
PDF
Tech Webinar: Angular 2, Introduction to a new framework
Codemotion
 
PPTX
Angular 5
Bartłomiej Narożnik
 
PDF
Angular2 - In Action
Sebastian Pożoga
 
PPTX
AngularJS2 / TypeScript / CLI
Domenico Rutigliano
 
PPTX
Angular 2 - Better or worse
Vladimir Georgiev
 
PPTX
Angular2
Oswald Campesato
 
An introduction to Angular2
Apptension
 
Introduction to Angular 2
Knoldus Inc.
 
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Codemotion
 
Angular2 workshop
Nir Kaufman
 
Building Universal Applications with Angular 2
Minko Gechev
 
Angular js 2
Ran Wahle
 
Angular2 with TypeScript
Rohit Bishnoi
 
Angular 2 Essential Training
Patrick Schroeder
 
Angular 2: core concepts
Codemotion
 
Angular2 for Beginners
Oswald Campesato
 
Angular Dependency Injection
Nir Kaufman
 
Angular 2 Crash Course
Elisha Kramer
 
2 years of angular: lessons learned
Dirk Luijk
 
Async patterns in javascript
Ran Wahle
 
Tech Webinar: Angular 2, Introduction to a new framework
Codemotion
 
Angular2 - In Action
Sebastian Pożoga
 
AngularJS2 / TypeScript / CLI
Domenico Rutigliano
 
Angular 2 - Better or worse
Vladimir Georgiev
 
Ad

Viewers also liked (18)

PDF
(Have a) rest with Laravel
Commit University
 
PDF
Commit University - Microsoft Azure
Commit University
 
PDF
Getting Started with Angular 2
FITC
 
PDF
Windows Azure Platform
Soumow Dollon
 
KEY
PHPSpec BDD for PHP
Marcello Duarte
 
PPTX
Angular 2.0
Nitin Giri
 
PPTX
Angular 2 a traveler's diary
Shavit Cohen
 
PPTX
Brief intro 2 to angular 2
Selasie Hanson
 
PDF
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
JSC “Arcadia Inc”
 
PPTX
PPT on Angular 2 Development Tutorial
Paddy Lock
 
PDF
Introduction to angular 2
Dhyego Fernando
 
PPTX
Angular 2 with typescript
Tayseer_Emam
 
PDF
Get that Corner Office with Angular 2 and Electron
Lukas Ruebbelke
 
PPTX
An afternoon with angular 2
Mike Melusky
 
PPTX
Angular 2
Nigam Goyal
 
PDF
The evolution of Angular 2 @ AngularJS Munich Meetup #5
Johannes Weber
 
PDF
Angular 2 for Java Developers
Yakov Fain
 
PPT
Silverlight
Soumow Dollon
 
(Have a) rest with Laravel
Commit University
 
Commit University - Microsoft Azure
Commit University
 
Getting Started with Angular 2
FITC
 
Windows Azure Platform
Soumow Dollon
 
PHPSpec BDD for PHP
Marcello Duarte
 
Angular 2.0
Nitin Giri
 
Angular 2 a traveler's diary
Shavit Cohen
 
Brief intro 2 to angular 2
Selasie Hanson
 
AzovDevMeetup 2016 | Angular 2: обзор | Александр Шевнин
JSC “Arcadia Inc”
 
PPT on Angular 2 Development Tutorial
Paddy Lock
 
Introduction to angular 2
Dhyego Fernando
 
Angular 2 with typescript
Tayseer_Emam
 
Get that Corner Office with Angular 2 and Electron
Lukas Ruebbelke
 
An afternoon with angular 2
Mike Melusky
 
Angular 2
Nigam Goyal
 
The evolution of Angular 2 @ AngularJS Munich Meetup #5
Johannes Weber
 
Angular 2 for Java Developers
Yakov Fain
 
Silverlight
Soumow Dollon
 
Ad

Similar to Commit University - Exploring Angular 2 (20)

PPTX
Introduction to Angular2
Ivan Matiishyn
 
PPTX
Angular 2 - a New Hope
Sami Suo-Heikki
 
PDF
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
PPTX
mean stack
michaelaaron25322
 
PDF
Meetup SkillValue - Angular 6 : Bien démarrer son application
Thibault Even
 
PPTX
Angular 2 Migration - JHipster Meetup 6
William Marques
 
PDF
better-apps-angular-2-day1.pdf and home
ChethanGowda886434
 
PPTX
Angular 2 in-1
GlobalLogic Ukraine
 
PPTX
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
PDF
Technozaure - Angular2
Demey Emmanuel
 
PDF
Angular 4 for Java Developers
Yakov Fain
 
PDF
Angular 2 - Core Concepts
Fabio Biondi
 
PPTX
Angular IO
Jennifer Estrada
 
PPTX
Peggy angular 2 in meteor
LearningTech
 
PDF
Angular 2.0 - What to expect
Allan Marques Baptista
 
PPTX
Angular 2
alinabiliashevych
 
PPTX
Angular1x and Angular 2 for Beginners
Oswald Campesato
 
PDF
Angular 16 – the rise of Signals
Coding Academy
 
PDF
angular fundamentals.pdf angular fundamentals.pdf
NuttavutThongjor1
 
Introduction to Angular2
Ivan Matiishyn
 
Angular 2 - a New Hope
Sami Suo-Heikki
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
mean stack
michaelaaron25322
 
Meetup SkillValue - Angular 6 : Bien démarrer son application
Thibault Even
 
Angular 2 Migration - JHipster Meetup 6
William Marques
 
better-apps-angular-2-day1.pdf and home
ChethanGowda886434
 
Angular 2 in-1
GlobalLogic Ukraine
 
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
Technozaure - Angular2
Demey Emmanuel
 
Angular 4 for Java Developers
Yakov Fain
 
Angular 2 - Core Concepts
Fabio Biondi
 
Angular IO
Jennifer Estrada
 
Peggy angular 2 in meteor
LearningTech
 
Angular 2.0 - What to expect
Allan Marques Baptista
 
Angular1x and Angular 2 for Beginners
Oswald Campesato
 
Angular 16 – the rise of Signals
Coding Academy
 
angular fundamentals.pdf angular fundamentals.pdf
NuttavutThongjor1
 

More from Commit University (20)

PDF
Accessibilità ed equità digitale: un impegno, non una scelta
Commit University
 
PDF
GitHub Copilot:vediamo chi comanda - Commit University.pdf
Commit University
 
PDF
Contract Driven Development - Branch 2024.pdf
Commit University
 
PPTX
Cybersecurity & AI: Illusioni e Speranze
Commit University
 
PDF
Migliorare la Developer Experience in un mondo Cloud Native
Commit University
 
PPTX
Scopri come sfruttare la potenza della Hybrid RAG
Commit University
 
PDF
Introduzione a AWS Forecast e SageMaker DeepAR: Prevedere la Domanda con il M...
Commit University
 
PDF
Oltre l'hype: vulnerabilità e limiti dell'intelligenza artificiale.pdf
Commit University
 
PPTX
Alla scoperta dei Vector Database e dei RAG
Commit University
 
PDF
Nell’iperspazio con Rocket: il Framework Web di Rust!
Commit University
 
PDF
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Commit University
 
PDF
Breaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdf
Commit University
 
PDF
Accelerating API Development: A Pit Stop with Gin-Gonic in Golang-Slide.pdf
Commit University
 
PDF
Slide-10years.pdf
Commit University
 
PDF
Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...
Commit University
 
PDF
Vue.js slots.pdf
Commit University
 
PPTX
Commit - Qwik il framework che ti stupirà.pptx
Commit University
 
PPTX
Sviluppare da zero una Angular Web App per la PA
Commit University
 
PDF
Backstage l'Internal Developer Portal Open Source per una migliore Developer ...
Commit University
 
PDF
Prisma the ORM that node was waiting for
Commit University
 
Accessibilità ed equità digitale: un impegno, non una scelta
Commit University
 
GitHub Copilot:vediamo chi comanda - Commit University.pdf
Commit University
 
Contract Driven Development - Branch 2024.pdf
Commit University
 
Cybersecurity & AI: Illusioni e Speranze
Commit University
 
Migliorare la Developer Experience in un mondo Cloud Native
Commit University
 
Scopri come sfruttare la potenza della Hybrid RAG
Commit University
 
Introduzione a AWS Forecast e SageMaker DeepAR: Prevedere la Domanda con il M...
Commit University
 
Oltre l'hype: vulnerabilità e limiti dell'intelligenza artificiale.pdf
Commit University
 
Alla scoperta dei Vector Database e dei RAG
Commit University
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Commit University
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Commit University
 
Breaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdf
Commit University
 
Accelerating API Development: A Pit Stop with Gin-Gonic in Golang-Slide.pdf
Commit University
 
Slide-10years.pdf
Commit University
 
Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...
Commit University
 
Vue.js slots.pdf
Commit University
 
Commit - Qwik il framework che ti stupirà.pptx
Commit University
 
Sviluppare da zero una Angular Web App per la PA
Commit University
 
Backstage l'Internal Developer Portal Open Source per una migliore Developer ...
Commit University
 
Prisma the ORM that node was waiting for
Commit University
 

Recently uploaded (20)

PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
Activate_Methodology_Summary presentatio
annapureddyn
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Explanation about Structures in C language.pptx
Veeral Rathod
 

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