Angular

Fundamentals

Luis Aviles
@luixaviles

It's Just Angular

Angular

How can I start?

Angular

  • Install CLI tool for Angular
npm install -g @angular/cli@latest

Angular CLI

What is it?

Angular CLI

  • Scaffold
  • Preview
  • Local build
  • Local Testing
    • ​Unit tests
    • E2E tests

Angular CLI

Create a new Project

Angular CLI

Create a new Project

ng new <project-name> [options]

Angular CLI

Create a new Project

ng new my-project-name --skip-install
yarn install
cd my-project-name

Angular CLI

Creating a Component

ng g component my-new-component

Angular CLI

Creating a Directive

ng g directive my-new-directive

Angular CLI

Creating a Pipe

ng g pipe my-new-pipe

Angular

Pipes

Pipes

  • Pipes transform displayed values within a template.
  • A pipe takes in data as input and transforms it to a desired output
<p>The hero's birthday is {{ birthday | date }}</p>

Pipes

  • DatePipe
  • UpperCasePipe
  • LowerCasePipe
  • CurrencyPipe
  • PercentPipe

Built-in pipes

Pipes

Built-in pipes

Pipes

Creating custom Pipes

ng g pipe my-custom-pipe

Pipes

Creating custom Pipes

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

@Pipe({
  name: 'myCustomPipe'
})
export class MyCustomPipe implements PipeTransform {

  transform(value: any, args?: any): any {
     // return something.
  }

}

Angular CLI

Creating a Service

ng g service my-new-service

Angular CLI

Creating a Class

ng g class my-new-class

Angular CLI

Creating an Interface

ng g interface my-new-interface

Angular CLI

Creating an Enum

ng g enum my-new-enum

Architecture Overview

Angular CLI

Creating a Module

ng g module my-module

Angular Material

Angular Material

Using Components

Angular

Displaying data

Angular

interpolation

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My name is: {{name}}</h2>
  `
})
export class AppComponent {
  title = 'Welcome';
  name = 'Luis';
}

Angular

property binding

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h1 [innerHTML]="title"></h1>
      <input type="text" [value]="text">
      <div>{{text}}</div>
    </div>
  `
})
export class AppComponent {
  title = 'Welcome';
  text = 'Luis';
}

Angular

binding to user events

import { Component } from '@angular/core';
@Component({
  selector: 'click-me',
  template: `
    <button (click)="onClickMe()">Click me!</button>
    {{clickMessage}}
  `
})
export class AppComponent{
  clickMessage = '';

  onClickMe() {
    this.clickMessage = 'You are my hero!';
  }
}

Angular

$event object

import { Component } from '@angular/core';
@Component({
  selector: 'click-me',
  template: `
    <input (keyup)="onKey($event)">
    <p>{{values}}</p>
  `
})
export class AppComponent{
  values = '';

  onKey(event:any) {
    this.values += event.target.value + ' | ';
  }
}

Angular

Dependency Injection(DI)

Angular

Dependency Injection

  • Dependency Injection is a design pattern that passes an object as dependencies in different components across the application.
  • It creates a new instance of class along with its required dependencies

Angular

Dependency Injection

// hero-list.component.ts
import { Component }   from '@angular/core';
import { Hero }        from './hero';
import { HeroService } from './hero.service';

@Component({
  selector: 'hero-list',
  template: `
  <div *ngFor="let hero of heroes">
    {{hero.id}} - {{hero.name}}
  </div>
  `
})
export class HeroListComponent {
  heroes: Hero[];
  constructor(heroService: HeroService) {
    this.heroes = heroService.getHeroes();
  }
}

Angular

Dependency Injection

// hero.service.ts
import { Injectable } from '@angular/core';
import { HEROES }     from './mock-heroes';

@Injectable()
export class HeroService {
  getHeroes() { return HEROES;  }
}

Angular

No Dependency Injection

// hero-list.component.ts
import { Component }   from '@angular/core';
import { HEROES }      from './mock-heroes';

@Component({
  selector: 'hero-list',
  template: `
  <div *ngFor="let hero of heroes">
    {{hero.id}} - {{hero.name}}
  </div>
  `
})
export class HeroListComponent {
  heroes = HEROES;
}

Angular

Why @Injectable()?

  • @Injectable() marks a class as available to an injector for instantiation

Angular

Promises

Promises

  • The Promise object is used for asynchronous computations.
  • A Promise represents a value which may be available now, or in the future, or never.
    • ​It can return a result
    • It can return an error

Promises

resolve()

// hero.service.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
}

Promises

then() method

// app.component.ts
@Component({
    // More code goes here
})
export class AppComponent implements OnInit {
  heroes: Hero[];
  constructor(private heroService: HeroService) { }
  
  getHeroes(): void {
    this.heroService.getHeroes()
        .then(heroes => this.heroes = heroes);
  }
  
  ngOnInit(): void {
    this.getHeroes();
  }
}

Promises

reject()

// hero.service.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.reject('Cannot connect with the server');    
  }
}

Promises

Error catch

// app.component.ts
@Component({
  // More code goes here
})
export class AppComponent implements OnInit {
  heroes: Hero[];
  constructor(private heroService: HeroService) { }
  
  getHeroes(): void {
    this.heroService.getHeroes()
        .then(heroes => this.heroes = heroes);
        .catch(error => {
            console.error('Error', error);
        });
  }
  
  ngOnInit(): void {
    this.getHeroes();
  }
}

Observer
Pattern

Reactive
Programming

ReactiveX

ReactiveX

ReactiveX

ReactiveX

Angular

HTTP Services

HTTP Services

HTTP Services

class HttpClient {
  request(first: string|HttpRequest<any>, url?: string, options: {...}): 
      Observable<any>
  delete(url: string, options: {...}): Observable<any>
  get(url: string, options: {...}): Observable<any>
  head(url: string, options: {...}): Observable<any>
  jsonp<T>(url: string, callbackParam: string): Observable<T>
  options(url: string, options: {...}): Observable<any>
  patch(url: string, body: any|null, options: {...}): Observable<any>
  post(url: string, body: any|null, options: {...}): Observable<any>
  put(url: string, body: any|null, options: {...}): Observable<any>
}

Using HttpClient

// app.module.ts:
 
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
 
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
 
@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

Using HttpClient

@Component(...)
export class MyComponent implements OnInit {
 
  results: string[];
 
  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}
 
  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

Angular

Components
Interaction/ Communication

Angular

Pass data from parent to child

import { Component } from '@angular/core';
import { Hero } from './hero';

@Component({
  selector: 'hero-parent',
  template: `
    <h2>{{master}} controls {{heroes.length}} heroes</h2>
    <hero-child [hero]="heroObject">
    </hero-child>
  `
})
export class HeroParentComponent {
  heroObject = new Hero();
}

Angular

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

@Component({
  selector: 'hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service</p>
  `
})
export class HeroChildComponent {
  @Input() hero: Hero;
}

Pass data from parent to child

Angular

Parent listens child event

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

@Component({
  selector: 'vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <my-voter [name]="voter" (onVoted)="onVoted($event)">
    </my-voter>
  `
})
export class VoteTakerComponent {
  voter: 'Foo Bar';
  onVoted(agreed: boolean) {
    console.log('Voter agrees: ', agreed);
  }
}

Angular

Parent listens child event

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

@Component({
  selector: 'my-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="voted">Agree</button>
    <button (click)="vote(false)" [disabled]="voted">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() onVoted = new EventEmitter<boolean>();
  voted = false;

  vote(agreed: boolean) {
    this.onVoted.emit(agreed);
    this.voted = true;
  }
}

Angular

Routing & Navigation

Routing

  • Enter a URL in the address bar and the browser navigates to a corresponding page.
  • Click links on the page and the browser navigates to a new page.
  • Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.​

Application Navigation Model

Routing

Routing

RouterOutlet

  • Acts as a placeholder that Angular dynamically fills based on the current router state.
<router-outlet></router-outlet>

Angular

Forms

FormsModule

<input [(ngModel)]="username">

NgModel
two-way data binding

ngModel
more than two-way data binding

Angular

References & resources

Angular

Luis Aviles

Angular Bolivia

Angular Fundamentals

By Luis Aviles

Angular Fundamentals

Angular Fundamentals

  • 1,437