115
Patrick Schroeder

Angular 2 Essential Training

Embed Size (px)

Citation preview

Page 1: Angular 2 Essential Training

Patrick Schroeder

Page 2: Angular 2 Essential Training

Typescript

Components

NgModules

Data Binding

Directives

Pipes

Inputs / Outputs

Observables

Routing

and more…

What you’ll Learn

Page 3: Angular 2 Essential Training
Page 4: Angular 2 Essential Training

ES5

Dart

CoffeeScript

ES2015 or ES7

Typescript

So Many Options!

Page 5: Angular 2 Essential Training

SPA (single-page app)

o index.htmlDynamic, Rich, & Fast

Browser-Loaded

Cleaner Code

o if conditions, loops, vars

o data-binding {{ bindMe }}

What is Angular?

Page 6: Angular 2 Essential Training

Loading Content

Server

Application

Server

+

SQL

Dataset

Template

Browser

Final HTML page

Browser

Application

Server

+

SQL

Dataset

Template

Browser

Final HTML page

Page 7: Angular 2 Essential Training

Guiding Principles

Page 8: Angular 2 Essential Training

Fast Friendly Modern

Angular 2 Features

Page 9: Angular 2 Essential Training
Page 10: Angular 2 Essential Training

Fast

Angular 2 Features

Initial Loads

Change Detection

Rendering

Page 11: Angular 2 Essential Training

Friendly

Angular 2 Features

Simplified API

Better Patterns

Page 12: Angular 2 Essential Training

Modern

Angular 2 Features

Components

Responsive

Page 13: Angular 2 Essential Training

ES2015

Javascript Advances

Classes

Modules

Decorators

Page 14: Angular 2 Essential Training

Typescript

ES2015

ES7

Strong Typing

Page 15: Angular 2 Essential Training

Typescript Features

Page 16: Angular 2 Essential Training

White

ECMAScript 5

ECMAScript 2015

TypeScript

Typescript = All the JavaScript

Page 17: Angular 2 Essential Training

Creates Strong Typing

var myVar: string = “Happy”;

Strings, Booleans, Arrays

Type Annotations

Page 18: Angular 2 Essential Training

Function Function ParameterProperty

export class AppComponent {

pageTitle: string = “Welcome";

}

function isFalse: boolean {

return false;

}

function sayHello(input: string): string{

return “Hello " + input;

}

Type Examples

Function void

function isFalse: void {

console.log(‘my message’);

}

Page 19: Angular 2 Essential Training

Syntax Checking = Fewer Bugs

IDE Supporto code completion, highlighting, error checking

Strong Typing Benefits

Page 20: Angular 2 Essential Training

Enhanced JavaScript

Strong Typing

IDE Support

TypeScript Benefits

Page 21: Angular 2 Essential Training

Angular 2 Setup

Page 22: Angular 2 Essential Training

Developer Environment• editors and plugins

Get going!• angular.io Quickstart

Setup Revisited• file explanation

Setup

Page 23: Angular 2 Essential Training

Install Node.js

Text Editor

Install Plugins

Developer Environment

Page 24: Angular 2 Essential Training

Create Container

Closed System

Import / Export

Modules

Page 25: Angular 2 Essential Training

NgModules

Page 26: Angular 2 Essential Training

@NgModule

Load Components

Bootstrapping

NgModule

Page 27: Angular 2 Essential Training

NgModule

“Used in order to help us organize our application into cohesive blocks of functionality”

Page 28: Angular 2 Essential Training

NgModule

app.module.ts

import { NgModule } from ‘@angular/core’;

import { BrowserModule } from

‘@angular/platform-browser’;

import { AppComponent } from ‘./app.component’;

@NgModule({

imports: [ BrowserModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { } Class

Metadata

Import

Page 29: Angular 2 Essential Training

NgModule

app.module.ts

import { NgModule } from ‘@angular/core’;

import { BrowserModule } from

‘@angular/platform-browser’;

import { AppComponent } from ‘./app.component’;

@NgModule({

imports: [ BrowserModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

@NgModule()

@NgModule({

// compose Metadata

})

Page 30: Angular 2 Essential Training

Bootstrapping

Page 31: Angular 2 Essential Training

Bootstrapping

main.ts

import { platformBrowserDynamic } from

‘@angular/platform-browser-dynamic’;

import { AppModule } from ‘./app.module’;

const platform = platformBrowserDynamic();

platform.bootstrapModule(AppModule); bootstrap

const

Import

Page 32: Angular 2 Essential Training

Root Component

app.component.ts

import { Component } from ‘@angular/core’;

@Component({

selector: ‘my-app’,

template: `<h1>My First Angular App</h1>`

})

export class AppComponent {}

Page 33: Angular 2 Essential Training

Why Components?

Page 34: Angular 2 Essential Training

Composition

Decorators & Classes

Directives

Styles & Templates

Components

Page 35: Angular 2 Essential Training

Bootstrapper

main.ts

App Component

Sidebar Component

Posts Component

NavComponent

Component Structure

Widgets Component

Calendar Component

Page 36: Angular 2 Essential Training

Building Components

Page 37: Angular 2 Essential Training

Building Components

Component

Template Class Metadata

• View Layout

• HTML Code

• Supports View

• Contains Properties

and Methods

• Used inside @Decorator

• Extra instructions for

Angular

Page 38: Angular 2 Essential Training

Component

app.component.ts

import { Component } from ‘@angular/core’;

@Component({

selector: ‘bs-app’,

template: `

<h1>{{ pageTitle }}</h1>

<div>App Component Test</div>`

})

export class AppComponent {

pageTitle: string = “Dev Book Store”;

showBook(): void {

// method logic here

}

}

Class

Metadata

Import

Page 39: Angular 2 Essential Training

Component

app.component.ts

import { Component } from ‘@angular/core’;

@Component({

selector: ‘bs-app’,

template: `

<h1>{{ pageTitle }}</h1>

<div>App Component Test</div>`

})

export class AppComponent {

pageTitle: string = “Dev Book Store”;

showBook(): void {

// method logic here

}

}

@Component()

@Component({

// compose Metadata

})

Page 40: Angular 2 Essential Training

Data Binding

Template

Methods

Properties

Class

{{pageTitle}}

Page 41: Angular 2 Essential Training

1-way Binding• {{pageTitle}}

2-way Binding• [(ngModel)]=“searchFilter”

Event Binding• (click)=“hideImage()”

Types of Data Binding

Page 42: Angular 2 Essential Training

1-way Binding

Interpolation

Template

export class AppComponent {

pageTitle: string =

“Dev Book Store”;

}

Class

<h1>{{ pageTitle }}</h1>

Page 43: Angular 2 Essential Training

Property Binding

Template

<img [src]=“bookImageUrl”>

Element

Property

Class

Property

export class BookListComponent {

bookImageUrl: string = “app/images/656.jpg”

}

Class

1-way Binding

Page 44: Angular 2 Essential Training

2-way Binding

Template

export class AppComponent {

searchBox: string = “”;

}

Class

<input [(ngModel)]=“searchBox”>

[()]

Banana in a Box

Page 45: Angular 2 Essential Training

2-way Binding

import { FormsModule } from ‘@angular/forms’;

@NgModule({

imports: [

BrowserModule,

FormsModule

]

})

export class AppModule { }

AppModule

Page 46: Angular 2 Essential Training

NgModule

app.module.ts

import { NgModule } from ‘@angular/core’;

import { BrowserModule } from

‘@angular/platform-browser’;

import { AppComponent } from ‘./app.component’;

@NgModule({

imports: [ BrowserModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { } Class

Metadata

Import

Page 47: Angular 2 Essential Training

Event Binding

“Used to respond to user actions like button clicks.”

Page 48: Angular 2 Essential Training

Respond to User Actions• Button clicks

Event Binding

Page 49: Angular 2 Essential Training

Template

(click)=“hideImage()” export class AppComponent {

hideImage(): void {

this.showImage = !this.showImage;

}

}

Class

Event Binding

https://developer.mozilla.org/en-US/docs/Web/Events

Page 50: Angular 2 Essential Training

Directives

Page 51: Angular 2 Essential Training

Directives

“An HTML element or attributethat is used to enhance and extend our HTML”

Page 52: Angular 2 Essential Training

Component• <bs-app></bs-app>

Structural• NgIf, NgFor, NgStyle

Attribute• <p highlight></p>

Types of Directives

Page 53: Angular 2 Essential Training

Types of Directives

Custom Structuralwelcome.component.ts

@Component({

selector: ‘bs-welcome’

})

app.component.ts

@Component({

selector: ‘bs-app’,

template: <bs-welcome></bs-welcome>

})

*ngIf=“showImage”

*ngFor=“let book of books”

Add, Remove or Update view elements

<tr *ngFor=“let book of books”>

<td>{{ book.title }}</td>

<td>{{ book.author }}</td>

<td>{{ book.price }}</td>

</tr>

Page 54: Angular 2 Essential Training

Structural Directives

Page 55: Angular 2 Essential Training

NgIf

books-list.component.html

<img *ngIf=“showImage”>

Add, Remove or Update view elements

- with Booleans

- with Conditionals

Page 56: Angular 2 Essential Training

NgFor

- Instantiates a templateonce per item from an iterable.

- Can be array or object.- Repeats over list creating new templates.

Page 57: Angular 2 Essential Training

NgFor

*ngFor=“let book of books”

<tr *ngFor=“let book of books”>

<td>{{ book.title }}</td>

<td>{{ book.author }}</td>

</tr>

books: any[] = [

{ title: “Moby Dick”, author: “Herman Melville”},

{ title: “War and Peace”, author: “Leo Tolstoy”},

{ title: “Ulysses”, author: “James Joyce”}

]

Page 58: Angular 2 Essential Training

NgClass

books-list.component.html

<div [ngClass]=“{‘redClass’: showImage, ‘yellowClass’: !showImage}”>

Adds and removes CSS classes on an

HTML element

- used with Object to form Expressions

- with Arrays or Strings [ngClass]=“redClass”

Page 59: Angular 2 Essential Training

Pipes

Page 60: Angular 2 Essential Training

Pipes

“Allow us to transform or format our data”

Page 61: Angular 2 Essential Training

Built-In = | uppercase

Custom = | myPipeName

Pipes

Page 62: Angular 2 Essential Training

Using Pipes

Template

export class BooksListComponent {

books: any[] = [{

inStock: ‘yes’

}]

}

books-list.component.ts

<h1>{{ books.inStock | uppercase }}</h1>

YES

Page 63: Angular 2 Essential Training

Built-In Pipes

Page 64: Angular 2 Essential Training

Uppercase

Lowercase

Decimal

Currency

Date

Json

Built-in Pipes

Page 65: Angular 2 Essential Training

1. Create File

2. Import into AppModule

3. Use in Template

Custom Pipes

Page 66: Angular 2 Essential Training

Custom Pipes

Template

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({

name: ‘limitChar'

})

export class TruncatePipe implements PipeTransform {

transform(input: string, args: string[]) {

// Perform transformation here

return…

}

}

truncate.pipe.ts

<h1>{{ books.results | limitChar }}</h1>

import { NgModule } from ‘@angular/core’;

import { AppComponent } from ‘./app.component’;

import { TruncatePipe } from ‘./truncate.pipe.ts’;

@NgModule({

declarations: [ AppComponent

TruncatePipe ],

bootstrap: [ AppComponent ]

})

app.module.ts

Page 67: Angular 2 Essential Training

Interface

Page 68: Angular 2 Essential Training

Interface

“Used in Typescript to define data types for properties and methods”

Page 69: Angular 2 Essential Training

1. Definition

2. Examples

3. Use in App

Interface

Page 70: Angular 2 Essential Training

Interface

export interface IBook {

id: string;

name: string;

releaseDate: Date;

description: string;

author: string;

price: number;

imageUrl: string;

damaged(reason: string): void;

}Method

Properties

Export

Page 71: Angular 2 Essential Training

export interface IBook {

id: string;

name: string;

releaseDate: Date;

description: string;

author: string;

price: number;

imageUrl: string;

damaged(reason: string): void;

}

Interface

Page 72: Angular 2 Essential Training

Strong Typing

Better Tooling

Development Time

Why Interfaces?

Page 73: Angular 2 Essential Training

Lifecycle Hooks

Page 74: Angular 2 Essential Training

1. Definition

2. Most Used Hooks

3. Examples

Lifecycle Hooks

Page 75: Angular 2 Essential Training

Lifecycle Hooks

ComponentChild

Components

Removes & Watches

Page 76: Angular 2 Essential Training

OnInit• Perform component initialization

OnChanges• Perform action when values change

OnDestroy• Perform clean-up

Lifecycle Hooks

Page 77: Angular 2 Essential Training

Using Lifecycle Hooks

import { Component, OnInit } from '@angular/core';

@Component({

selector: ‘bs-books-list'

})

export class BooksListComponent implements OnInit {

ngOnInit() : void {

console.log(‘Inside OnInit’);

}

}

books-list.component.ts

Page 78: Angular 2 Essential Training

Inputs and Outputs

Page 79: Angular 2 Essential Training

1.Nested Components

2.@Input / @Output

3.Custom Events

Inputs and Outputs

Page 80: Angular 2 Essential Training

Nested Components

Page 81: Angular 2 Essential Training

Bootstrapper

main.ts

App Component

Sidebar Component

Posts Component

NavComponent

Sample Component Hierarchy

Widgets Component

Calendar Component

Child

Components

Send

Receive

Page 82: Angular 2 Essential Training

@Input

“Allows data to flow from parent component to child component”

Page 83: Angular 2 Essential Training

Inputs

Container Component

Nested Component

@Input() reviews: number; Input

Page 84: Angular 2 Essential Training

child_component.ts

export class ParentComponent {

books: any[] = [{

bookReviews: 15

}]

}

Input

parent_component.ts

import { Component, Input } from '@angular/core';

@Component({

selector: ‘child'

})

export class ChildComponent {

Input() reviews: number;

}

parent_component.html

<div><h1>Parent Title</h1>

<p>body text…</p>

<child [reviews]=“book.bookReviews”>

</child>

</div>

child_component.html

<div>

<p>{{ reviews }}</p>

</div>

Page 85: Angular 2 Essential Training

@Output

“Custom events that pass data from component to the outside world.”

Page 86: Angular 2 Essential Training

Output

Container Component

Nested Component

@Output() notify: EventEmitter<string> = newEventEmitter<string>(); Output

Page 87: Angular 2 Essential Training

EventEmitter

“Listens for something to happen and emits an event when triggered”

Page 88: Angular 2 Essential Training

EventEmitter

notify

Child Component

Publishes to Parent

new EventEmitter

this.notify.emit(‘send message’)

Parent Component

Subscribes to

Output

(notify)=“actionMethod()”

Page 89: Angular 2 Essential Training

child_component.ts

export class ParentComponent {

onNotifyClicked(message: string): void {

this.showMessage = message;

}

}

Output

parent_component.ts

import { Output, EventEmitter } from '@angular/core';

export class ChildComponent {

Output() notify: EventEmitter<string> =

new EventEmitter<string>();

onClick(): void {

this.notify.emit(‘Message from child’);

}

} parent_component.html

<div><h1>Parent Title</h1>

<p>{{ showMessage }}</p>

<child (notify)=“onNotifyClicked($event)”>

</child>

</div>

child_component.html

<div

(click)=“onClick()”>

<button>Click Me</button> </div>

Page 90: Angular 2 Essential Training

Generic

“Defines the type of an instance. Such as a object or function. Example: MyObj<string>”

Page 91: Angular 2 Essential Training

Services

Page 92: Angular 2 Essential Training

What are Services• Building

• Registering

• Injecting

Dependency Injection• Singleton

Constructor• Initial setup

Services

Page 93: Angular 2 Essential Training

Service

“Used to encapsulate logic that can be used across multiple components”

Page 94: Angular 2 Essential Training

Data Service Component

Injector

Page 95: Angular 2 Essential Training

Service

@NgModule({

imports: [ BrowserModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ],

providers: [ BookService ]

})

export class AppModule { }

book.service.ts

import { Injectable } from '@angular/core';

import { IBook } from ‘./models/book';

@Injectable()

export class BookService {

getBooks(): IBook[] {

// get all books

}

}

import { IBook } from ‘./models/book';

import { BookService } from ‘./book.service.ts';

export class BookComponent {

constructor(_bookService: BookService) { }

getAllBooks() {

this._bookService.getBooks()

}

}

app.module.ts book.component.ts

Page 96: Angular 2 Essential Training

Constructor

import { IBook } from ‘./models/book';

import { BookService } from ‘./book.service.ts';

export class BookComponent {

constructor(private _bookService: BookService) { }

getAllBooks() {

this._bookService.getBooks()

}

}

book.component.ts

Page 97: Angular 2 Essential Training

Special Method

Initial Setup

No Return Value

Constructor

Page 98: Angular 2 Essential Training

HTTP & Observables

Page 99: Angular 2 Essential Training

HTTP

Request

Response

- http

- Observable

Page 100: Angular 2 Essential Training

Observables• compare to promises

Http Request• GET

• process as Observable

Subscribe• display data

HTTP & Observables

Page 101: Angular 2 Essential Training

Observables

Page 102: Angular 2 Essential Training

Observable

“An asynchronous stream of data we can subscribe to”

Page 103: Angular 2 Essential Training

price 3

price 2

price 1

Observables

Page 104: Angular 2 Essential Training

Single value

Not cancellable

Observable

Multiple values

Cancellable

Map, filter, reduce

Promisevs

Page 105: Angular 2 Essential Training

HTTP

Page 106: Angular 2 Essential Training

Using Http

import { HttpModule } from ‘@angular/http';

@NgModule({

imports: [ BrowserModule

HttpModule ],

declarations: [ AppComponent ],

bootstrap: [ AppComponent ],

providers: [ BookService ]

})

export class AppModule { }

book.service.ts

import { Injectable } from '@angular/core';

import { Http } from ‘@angular/http';

@Injectable()

export class BookService {

constructor(private _http: Http) { }

getBooks(): IBook[] {

return this._http

.get(‘api/books.json’)

.map((response: Response) => response.json())

}

}

app.module.ts

Page 107: Angular 2 Essential Training

Routing

Page 108: Angular 2 Essential Training

Simple Routing• <router-outlet>

routerLink• menu, buttons

Pass Parameters• book-details

Routing

Page 109: Angular 2 Essential Training

1.<base href=“/”>

2.import RouterModule

3.Add path’s

4.<router-outlet>

Routing

Page 110: Angular 2 Essential Training

Routing

import { RouterModule } from ‘@angular/router';

@NgModule({

imports: [ BrowserModule

RouterModule.forRoot([

{ path: “books”, component: BooksListComponent },

{ path: “”, redirectTo: “books”, pathMatch: “full” },

{ path: “**”, redirectTo: “books”, pathMatch: “full” }

]),

bootstrap: [ AppComponent ]

})

export class AppModule { }

index.html

<html>

<head>

<base href=“/”>

<router-outlet></router-outlet>

<!-- <bs-books-list></bs-books-list> -->

app.module.ts app.component.html

http://localhost:3000/books

Page 111: Angular 2 Essential Training

RouterLink

<a [routerLink]=“[‘/books’]”>All Books</a>

{ path: ‘books’, component: BooksListComponent }

http://localhost:3000/books

Page 112: Angular 2 Essential Training

1.new HomeComponent

2.set as default

3.add links to

‘home’ and ‘books’

Routing Challenge

Page 113: Angular 2 Essential Training

Routing with Parameters

import { RouterModule } from ‘@angular/router';

@NgModule({

imports: [ BrowserModule

RouterModule.forRoot([

{ path: “books”, component: BooksListComponent },

{ path: “book/:id”, component: BookDetailsComponent },

{ path: “”, redirectTo: “books”, pathMatch: “full” },

{ path: “**”, redirectTo: “books”, pathMatch: “full” }

]),

bootstrap: [ AppComponent ]

})

export class AppModule { }

app.module.ts

Page 114: Angular 2 Essential Training

Passing Route Parameters

books-list.component.html

{ path: “book/:id”, component: BookDetailsComponent }

app.module.ts

<h4>

<a [routerLink]=“[‘/book’, book.id]”>

{{ book.name }}

</a>

</h4>

Page 115: Angular 2 Essential Training

Passing Route Parameters

books-list.component.html

{ path: “book/:id”, component: BookDetailsComponent }

app.module.ts

<h4>

<a [routerLink]=“[‘/book’, book.id]”>

{{ book.name }}

</a>

</h4>