SlideShare a Scribd company logo
Angular2
Michał PrzyszczypkowskiAngular2
By Michał Przyszczypkowski
Background
revolution instead of evolution
currently in BETA (since December 2015)
release date not yet announced
Angular2
By Michał Przyszczypkowski
Typescript
Superset of JS (ES6)
Compiles to plain JS
Supported in all major IDE's
function greet(name: string):string {
return "Hello, " + name;
}
let greeting: string = greet("Mike");
Strongly typed
class Student {
public fullname : string;
private age: number;
private dontKnowWhatWillBeThere:any;
constructor(public firstname:string, public lastname:string) {
//...
}
}
Classes & interfaces
class Student {
public fullname : string;
private age: number;
private dontKnowWhatWillBeThere:any;
constructor(public firstname:string, public lastname:string) {
//...
}
}
Classes & interfaces
class Student {
lastname: string;
fullname : string;
constructor(firstname:string, lastname:string) {
this.firstname = firstname;
this.lastname = lastname;
}
}
interface Person {
firstname: string;
lastname: string;
}
Classes & interfaces
interface Person {
firstname: string;
lastname: string;
}
Classes & interfaces
function greeter(person : Person) {
return "Hello, " + person.firstname + " " + person.lastname;
}
let user: Person = new Student("Mike", "Someone");
interface Person {
firstname: string;
lastname: string;
}
Classes & interfaces
function greeter(person : Person) {
return "Hello, " + person.firstname + " " + person.lastname;
}
let user: Person = new Student("Mike", "Someone");
let user: Person = {firstname: 'Mike', lastname: 'Snow'}
Annotations / Decorators
Decorators are proposed as standard for ES
Already implemented in TS
Annotations / Decorators
@ExampleAnnotation({
annotationKey: annotationValue
})
export class ExampleClass {
}
Decorators are proposed as standard for ES
Already implemented in TS
Annotations / Decorators
@ExampleAnnotation({
annotationKey: annotationValue
})
export class ExampleClass {
}
Decorators are proposed as standard for ES
Already implemented in TS
@AnotherExampleAnnotation({
annotationKey: annotationValue
})
doSomething() {
//...
}
Modules
export interface Person {
name: string;
}
export class PeopleService {
getPeople(): People[] {
return [{name: 'Mike'}];
}
}
export const value:string = 'Something';
Modules
import * as library from "./module";
import { Person, PeopleService } from "./module";
console.log(library.value);
let peopleSrv = new PeopleService();
let people: Person[] = peopleSrv.getPeople();
export interface Person {
name: string;
}
export class PeopleService {
getPeople(): People[] {
return [{name: 'Mike'}];
}
}
export const value:string = 'Something';
Angular2
App is made of components
Angular2
App is made of components
Tree structure
Angular2
App is made of components
Tree structure
Concepts from AngularJS 1.x no longer
relevant
Angular2
App is made of components
Tree structure
Concepts from AngularJS 1.x no longer
relevant
$scope, $directive, $controller, $service,
$factory - no longer exist
Angular2
There is no $scope.$apply()
No need to use $timeout, $interval etc.
All events that may lead to bindings
changes are patched within library
We don't need to handle changes
detection anymore
Components
@Component({
selector: 'click-me',
templateUrl: 'template.html'
})
export class ClickMeComponent {
private label: string = 'Click there!';
onClickMe(){
alert('Hello.');
}
}
Components
@Component({
selector: 'click-me',
templateUrl: 'template.html'
})
export class ClickMeComponent {
private label: string = 'Click there!';
onClickMe(){
alert('Hello.');
}
}
properties
methods
component
config
Components
@Component({
selector: 'click-me',
templateUrl: 'template.html'
})
export class ClickMeComponent {
private label: string = 'Click there!';
onClickMe(){
alert('Hello.');
}
}
<body>
<click-me></click-me>
</body>
properties
methods
component
config
Selectors
@Component({
selector: 'click-me'
...
})
<click-me></click-me>
Selectors
@Component({
selector: 'click-me'
...
})
<click-me></click-me>
@Component({
selector: '[click-me]'
...
})
<div click-me=""></div>
Inputs
@Component({
selector: 'click-me',
templateUrl: 'template.html',
inputs: ['message']
})
export class ClickMeComponent {
private message: string;
onClickMe(){
alert(this.message);
}
}
Inputs
@Component({
selector: 'click-me',
templateUrl: 'template.html',
inputs: ['message']
})
export class ClickMeComponent {
private message: string;
onClickMe(){
alert(this.message);
}
}
<click-me message="Peekaboo"></click-me>
Outputs
@Component({
selector: 'click-me',
templateUrl: 'template.html',
outputs: ['onClicked']
})
export class ClickMeComponent {
private onClicked: EventEmitter<string> = new EventEmitter<string>();
onClickMe(){
this.onClicked.emit("Hello");
}
}
Outputs
@Component({
selector: 'click-me',
templateUrl: 'template.html',
outputs: ['onClicked']
})
export class ClickMeComponent {
private onClicked: EventEmitter<string> = new EventEmitter<string>();
onClickMe(){
this.onClicked.emit("Hello");
}
}
<body>
<click-me (onClicked)="doSomething($event)"></click-me>
</body>
Styles
@Component({
selector: 'click-me',
templateUrl: 'template.html',
styles: [`.click-btn {
color: red;
}`]
})
export class ClickMeComponent {
...
}
Styles
@Component({
selector: 'click-me',
templateUrl: 'template.html',
styles: [`.click-btn {
color: red;
}`]
})
export class ClickMeComponent {
...
}
@Component({
selector: 'click-me',
templateUrl: 'template.html',
styles: [`.click-btn {
color: red;
}`],
encapsulation: ViewEncapsulation.None // Native / Emulated
})
export class ClickMeComponent {
...
}
Directives
@Directive({
selector: '[click-me]',
styles: [`.click-btn {
color: red;
}`]
})
export class ClickMeDirective {
...
}
Template language
@Component({
selector: 'click-me',
templateUrl: 'template.html'
})
export class ClickMeComponent {
private label: string = 'Click there!';
onClickMe(){
alert('Hello.');
}
}
Template language
@Component({
selector: 'click-me',
templateUrl: 'template.html'
})
export class ClickMeComponent {
private label: string = 'Click there!';
onClickMe(){
alert('Hello.');
}
}
<button (click)="onClickMe()">{{ label }}</button>
Template language
<click-me message="Peekaboo"></click-me>
Template language
<click-me message="Peekaboo"></click-me>
<click-me [message]="peekabooVariable"></click-me>
Template language
<click-me message="Peekaboo"></click-me>
<click-me [message]="peekabooVariable"></click-me>
<click-me [message]="peekabooVariable" (onClicked)="doSth($event)"></click-me>
Structural directives
<span *ngFor="#item of items"> {{ item.name }} </span>
Structural directives
<span *ngFor="#item of items; #index = index"> item no {{ index }} </span>
<span *ngFor="#item of items"> {{ item.name }} </span>
Structural directives
<span *ngFor="#item of items; #index = index"> item no {{ index }} </span>
<span *ngFor="#item of items"> {{ item.name }} </span>
explicit declaration
Structural directives
<span *ngFor="#item of items; #index = index"> item no {{ index }} </span>
<span *ngFor="#item of items"> {{ item.name }} </span>
<span *ngIf="isVisible"> conditional item </span>
explicit declaration
Build-in directives
<span [class.blue]="isBlue"> TEXT </span>
Build-in directives
<span [class.blue]="isBlue"> TEXT </span>
<span [style.backgroundColor]="colorVariable"> TEXT </span>
Build-in directives
<span [class.blue]="isBlue"> TEXT </span>
<span [style.backgroundColor]="colorVariable"> TEXT </span>
<span [style.display]="isHidden ? 'none' : 'block'"> TEXT </span>
Build-in directives
<span [class.blue]="isBlue"> TEXT </span>
<span [style.backgroundColor]="colorVariable"> TEXT </span>
<span [hidden]="isHidden"> TEXT </span>
<span [style.display]="isHidden ? 'none' : 'block'"> TEXT </span>
Build-in directives
<span [class.blue]="isBlue"> TEXT </span>
<span [style.backgroundColor]="colorVariable"> TEXT </span>
<span [hidden]="isHidden"> TEXT </span>
<span (click)="onClick()" (mouseenter)="onMouseEnter()"> TEXT </span>
<span [style.display]="isHidden ? 'none' : 'block'"> TEXT </span>
Transclusion
<example-component>
<h1>Inner title</h1>
<span>Inner text</span>
</example-component>
Transclusion
<div class="example-component-template">
<h1>Outer title</h1>
<ng-content></ng-content>
</div>
<example-component>
<h1>Inner title</h1>
<span>Inner text</span>
</example-component>
content will go
there
Transclusion
<div class="example-component-template">
<h1>Outer title</h1>
<ng-content></ng-content>
</div>
<example-component>
<h1>Inner title</h1>
<span>Inner text</span>
</example-component>
<div class="example-component-template">
<h1>Outer title</h1>
<h1>Inner title</h1>
<span>Inner text</span>
</div>
content will go
there
Services
class ItemsRepository {
private items: Product[];
getItems(): Products[] {
return this.items;
}
}
class ItemsRepository {
private items: Product[];
getItems(): Products[] {
return this.items;
}
}
import {ItemsRepository} from '../itemsRepo'
@Component({
selector: 'click-me',
templateUrl: 'template.html',
providers: [ItemsRepository]
})
export class ItemList {
private items: Product[];
constructor(repo: ItemsRepository) {
this.items = repo.getItems();
}
}
Dependency Injection
class ItemsRepository {
private items: Product[];
getItems(): Products[] {
return this.items;
}
}
import {ItemsRepository} from '../itemsRepo'
@Component({
selector: 'click-me',
templateUrl: 'template.html',
providers: [ItemsRepository]
})
export class ItemList {
private items: Product[];
constructor(repo: ItemsRepository) {
this.items = repo.getItems();
}
}
Dependency Injection
first import
class ItemsRepository {
private items: Product[];
getItems(): Products[] {
return this.items;
}
}
import {ItemsRepository} from '../itemsRepo'
@Component({
selector: 'click-me',
templateUrl: 'template.html',
providers: [ItemsRepository]
})
export class ItemList {
private items: Product[];
constructor(repo: ItemsRepository) {
this.items = repo.getItems();
}
}
Dependency Injection
first import
set as provider
class ItemsRepository {
private items: Product[];
getItems(): Products[] {
return this.items;
}
}
import {ItemsRepository} from '../itemsRepo'
@Component({
selector: 'click-me',
templateUrl: 'template.html',
providers: [ItemsRepository]
})
export class ItemList {
private items: Product[];
constructor(repo: ItemsRepository) {
this.items = repo.getItems();
}
}
Dependency Injection
first import
set as provider
inject in
constructor
App
ItemsEdition ItemsList
C D
E
Providers visibility
App
ItemsEdition ItemsList
C D
E
providers: [ItemsRepository]
Providers visibility
App
ItemsEdition ItemsList
C D
E
providers: [ItemsRepository]
Whole app share the
same instance of
ItemsRepository service
Providers visibility
App
ItemsEdition ItemsList
C D
E
App
ItemsEdition ItemsList
C D
E
providers: [ItemsRepository]
providers: [ItemsRepository]
App
ItemsEdition ItemsList
C D
E
providers: [ItemsRepository]
providers: [ItemsRepository]
Each subtree has its own
instance of service.
class Api {
loadItems(): Products[] {
return this.items;
}
}
DI between services
import {Api} from "./api";
@Injectable()
class ItemsRepository {
constructor(private api:Api) { }
getItems(): Products[] {
this.api.loadItems();
}
}
Mocking providers
import {FakeItemsRepository} from '../fakeItemsRepo'
@Component({
selector: 'click-me',
templateUrl: 'template.html',
providers: [
provide(ItemsRepository, {useClass: FakeItemsRepository})
]
})
export class ItemList {
// ...
}
Mocking providers
import {FakeItemsRepository} from '../fakeItemsRepo'
@Component({
selector: 'click-me',
templateUrl: 'template.html',
providers: [
provide(ItemsRepository, {useClass: FakeItemsRepository})
]
})
export class ItemList {
// ...
}
use custom
provider
Routing
Routing
routes point to components
Routing
routes point to components
@RouteConfig([
{path: '/', component: Home, as: 'Home'},
{path: '/list', component: Items, as: 'List'}
]}
@Component({..})
class ...
Routing
routes point to components
@RouteConfig([
{path: '/', component: Home, as: 'Home'},
{path: '/list', component: Items, as: 'List'}
]}
@Component({..})
class ...
<router-outlet></router-outlet>
Routing parameters
@RouteConfig([
{path: '/item/:id', component: Item, as: 'Item'}
]}
Routing parameters
@RouteConfig([
{path: '/item/:id', component: Item, as: 'Item'}
]}
constructor(params:RouteParams) {
let routeParamValue:string = params.get('id');
}
Nested routes
Nested routes
Nested routes
<router-outlet>
Nested routes
<router-outlet>
Nested routes
<router-outlet> <router-outlet>
Nested routes
<router-outlet> <router-outlet> <router-outlet>
Nested routes
@RouteConfig([
{path: '/home', component: Home, as: 'Home'},
{path: '/items/...', component: Items, as: 'List'}
]}
@Component({..})
class ...
<router-outlet></router-outlet>
Nested routes
@RouteConfig([
{path: '/home', component: Home, as: 'Home'},
{path: '/items/...', component: Items, as: 'List'}
]}
@Component({..})
class ...
<router-outlet></router-outlet>
@RouteConfig([
{path: '/add', component: AddItem, as: 'Add'},
{path: '/edit/:id', component: EditItem, as: 'Edit'}
]}
@Component({..})
class ...
<router-outlet></router-outlet>
Nested routes
/home /items/add /items/edit/1
Home
Items ItemsAddItem EditItem
Navigation
<a [routerLink]="['Home']">Home</a>
Navigation
<a [routerLink]="['Home']">Home</a>
let router:Router;
router.navigate(['Home']);
Navigation
<a [routerLink]="['Home']">Home</a>
let router:Router;
router.navigate(['Home']);
<a [routerLink]="['Items', 'Add']">Home</a>
Navigation
<a [routerLink]="['Home']">Home</a>
let router:Router;
router.navigate(['Home']);
<a [routerLink]="['Items', 'Add']">Home</a>
<a [routerLink]="['Items', 'Edit', {id: 99}]">Home</a>
Navigation
<a [routerLink]="['Home']">Home</a>
let router:Router;
router.navigate(['Home']);
<a [routerLink]="['Items', 'Add']">Home</a>
<a [routerLink]="['Items', 'Edit', {id: 99}]">Home</a>
<a [routerLink]="['Item', {id:99}, 'Edit']">Home</a>
/item/:id/edit
Lifecycle hooks
Lifecycle hooks
@Component({...})
export class ComponentClass implements OnInit, OnDestroy {
ngOnInit():any {
...
}
ngOnDestroy():any {
...
}
}
How to hook?
Component lifecycle hooks
OnInit
OnDestroy
DoCheck
OnChanges
AfterContentInit
AfterContentChecked
AfterViewInit
AfterViewChecked
Router lifecycle hooks
CanActivate
OnActivate
CanDeactivate
OnDeactivate
OnReuse
https://angular.io/docs/ts/latest/guide/
http://blog.thoughtram.io/
Resources
Thank you.
Questions?

More Related Content

PDF
Angular2 workshop
PDF
Angular2 with TypeScript
PDF
Commit University - Exploring Angular 2
PDF
Angular2 - In Action
PDF
Angular 2 - The Next Framework
PDF
Data Flow Patterns in Angular 2 - Sebastian Müller
PPTX
Angular js 2
PPTX
Angular2 + rxjs
Angular2 workshop
Angular2 with TypeScript
Commit University - Exploring Angular 2
Angular2 - In Action
Angular 2 - The Next Framework
Data Flow Patterns in Angular 2 - Sebastian Müller
Angular js 2
Angular2 + rxjs

What's hot (20)

PDF
How Angular2 Can Improve Your AngularJS Apps Today!
PDF
The productive developer guide to Angular 2
PPTX
Migrating an application from Angular 1 to Angular 2
PDF
Introduction to Angular 2
PDF
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
PPTX
Introduction to Angular2
PDF
Angular 2 Crash Course
ODP
Introduction to Angular 2
PDF
Exploring Angular 2 - Episode 2
PPTX
Async patterns in javascript
PDF
Boosting Angular runtime performance
PDF
Migrating to Angular 2
PDF
Angular Weekend
PDF
Building Universal Applications with Angular 2
PPTX
Angular2 for Beginners
PPTX
Peggy angular 2 in meteor
PDF
Angular2 with type script
PDF
Angular Dependency Injection
PDF
The evolution of Angular 2 @ AngularJS Munich Meetup #5
How Angular2 Can Improve Your AngularJS Apps Today!
The productive developer guide to Angular 2
Migrating an application from Angular 1 to Angular 2
Introduction to Angular 2
Understanding Angular 2 - Shmuela Jacobs - Codemotion Milan 2016
Introduction to Angular2
Angular 2 Crash Course
Introduction to Angular 2
Exploring Angular 2 - Episode 2
Async patterns in javascript
Boosting Angular runtime performance
Migrating to Angular 2
Angular Weekend
Building Universal Applications with Angular 2
Angular2 for Beginners
Peggy angular 2 in meteor
Angular2 with type script
Angular Dependency Injection
The evolution of Angular 2 @ AngularJS Munich Meetup #5
Ad

Similar to An introduction to Angular2 (20)

PDF
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
PDF
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
PDF
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
PDF
준비하세요 Angular js 2.0
PDF
Hidden Docs in Angular
PPTX
2 years of angular: lessons learned
PDF
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
PDF
Angular2 Development for Java developers
PDF
XebiConFr 15 - Brace yourselves Angular 2 is coming
PDF
Exploring Angular 2 - Episode 1
ODP
To inject or not to inject: CDI is the question
PDF
angular fundamentals.pdf angular fundamentals.pdf
PPTX
SenchaCon 2016: Want to Use Ext JS Components with Angular 2? Here’s How to I...
PDF
How to Mess Up Your Angular UI Components
PDF
Implicit parameters, when to use them (or not)!
PDF
It's complicated, but it doesn't have to be: a Dagger journey
PDF
Angular js 2.0, ng poznań 20.11
PDF
Angular 2 introduction
PDF
React: JSX and Top Level API
PDF
Stencil the time for vanilla web components has arrived
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
준비하세요 Angular js 2.0
Hidden Docs in Angular
2 years of angular: lessons learned
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
Angular2 Development for Java developers
XebiConFr 15 - Brace yourselves Angular 2 is coming
Exploring Angular 2 - Episode 1
To inject or not to inject: CDI is the question
angular fundamentals.pdf angular fundamentals.pdf
SenchaCon 2016: Want to Use Ext JS Components with Angular 2? Here’s How to I...
How to Mess Up Your Angular UI Components
Implicit parameters, when to use them (or not)!
It's complicated, but it doesn't have to be: a Dagger journey
Angular js 2.0, ng poznań 20.11
Angular 2 introduction
React: JSX and Top Level API
Stencil the time for vanilla web components has arrived
Ad

More from Apptension (7)

PDF
Configuring Django projects for multiple environments
PDF
White Space
PPTX
Team Happiness - O szczęściu w zespole
PPTX
D3.js - A picture is worth a thousand words
PDF
Universal Javascript in React
PDF
Testerzy na orbicie
PDF
AngularJS - podstawy
Configuring Django projects for multiple environments
White Space
Team Happiness - O szczęściu w zespole
D3.js - A picture is worth a thousand words
Universal Javascript in React
Testerzy na orbicie
AngularJS - podstawy

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PPTX
Big Data Technologies - Introduction.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Cloud computing and distributed systems.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Machine learning based COVID-19 study performance prediction
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Big Data Technologies - Introduction.pptx
MYSQL Presentation for SQL database connectivity
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Advanced methodologies resolving dimensionality complications for autism neur...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The AUB Centre for AI in Media Proposal.docx
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Cloud computing and distributed systems.
Dropbox Q2 2025 Financial Results & Investor Presentation

An introduction to Angular2