Angular 2

Angular2

Angular2

Why not AngularJS?

TypeScript

It's not really a ES6 superset...😩

photo by ngBook-2

function greetText(name: string): string {
    return "Hello " + name;
}

Can I use Angular without TS?

Technical debt

Components

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

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {
  constructor() { }

  ngOnInit() {
  }
}
<app-hello-world></app-hello-world>
<app-hello-world>
    <search-bar></search-bar>
    <results></results>
</app-hello-world>

How Components communicate?

Attributes

@Input

<app-hello-world>
    <search-bar></search-bar>
    <results [list]="myResults"></results>
</app-hello-world>

Events

@Output

<app-hello-world>
    <search-bar (onSearch)="search($event)"></search-bar>
    <results [list]="myResults"></results>
</app-hello-world>

UI Components are Microservices for frontend development

Providers

In Providers you should put everything that it's not bounded to the view

@Injectable
export default class Logger {
    log(param){
        console.log(param);
    }
}
@Injectable
export default class Logger {
    log(param){
        console.log(param);
    }
}
import { Component, OnInit } from '@angular/core';
import Logger from './logger';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {
  constructor(private logger: Logger) { }

  ngOnInit() {
  }
}

RxJs

Rx stands for Reactive eXtensions

With Rx you manage all events like streams with a common interface called Observable

You can manipulate streams from whatever source they come from (user input, http, route change)

Useful links

Thanks!

angular-cli

https://github.com/angular/angular-cli

CLI Tools for quickly generate Angular projects and elements

Installation

npm install -g angular-cli

New project

ng new PROJECT_NAME

Blueprints

ng g component NAME
ng g service NAME
ng g pipe NAME
ng g directive NAME

Tests

ng test

Build

ng build

Pipes

A Pipe is a way to transform displayed values within a template

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

@Pipe({
  name: 'celsius'
})
export class CelsiusPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    //°C = K − 273,15
    const kelvin = parseFloat(value);
    if(isNaN(kelvin)){
      return 0;
    }
    return kelvin - 273.15
  }

}
<span>{{temperature | celsius}}</span>

Directives

An Attribute directive changes the appearance or behavior of a DOM element.

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}
<p [myHighlight]>I am yellow!</p>

Built-in Directives

NgIf

<div *ngIf="false">never displayed</div>
<div *ngIf="a > b">displayed if a is more than b</div>
<div *ngIf="str === 'yes'">displayed if str holds the string "yes"</div>

NgStyle

<div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
      Uses fixed white text on blue background
</div>

NgClass

.bordered {
    border: 1px dashed black; background-color: #eee;
}

<div [ngClass]="{bordered: false}">This is never bordered</div>
<div [ngClass]="{bordered: true}">This is always bordered</div>

NgFor

<!-- on the component this.cities = ['Miami', 'Sao Paulo', 'New York']; -->

<div class="ui list" *ngFor="let c of cities"> 
    <div class="item">{{ c }}</div>
</div>

NgModel

<input
    type="text"
    placeholder="Product Name"
    [(ngModel)]="productName">

NgModel is a special directive: it binds a model to a form

Single Page Applications

A single-page application (SPA) is a web application or web site that fits on a single web page with the goal of providing a user experience similar to that of a desktop application.

Wikipedia

http://localhost:8100/#/login

Photo by Microsoft

How does it work?

Before you commit to a framework, make sure you could write it. 

Uncle Bob

Routes

Every route match with a component. When the URL changes the right component replaces the <router-outlet/>

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'detail',
    component: DetailComponent,
  }
];

Definition

<a routerLink="/detail">Go To Detail</a>

Navigation (template)

this.router.navigate(['/detail'])

Navigation (code)

@Injectable()
export class LoggedInGuardService implements CanActivate{

  constructor(
    private router: Router, 
    private currentUserService: CurrentUserService) { }

  canActivate(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot) {
        if(!this.currentUserService.get()){
          this.router.navigate(['/login']);
          return false;
        }
        return true;
    }

}

Guarding Routes

const routes: Routes = [
  {
    path: 'protected',
    component: ProtectedComponent,
    canActivate:[LoggedInGuardService]
  }
];

Guarding Routes

Angular 2

By extrategy

Angular 2

  • 1,758