1 of 67

Angular Workshop

Part I. Fundamentals

2 of 67

CARLOS CABALLERO

PHD COMPUTER SCIENCE�VOCATIONAL TRAINING TEACHER

NPKILL

ANGULAR MÁLAGA

ANGULAR COMMUNITIES

3 of 67

@DotTechES

4 of 67

Table of Contents

What is Angular?

Standalone-Components

Communication between components (@Input/@Output)

Reactive Forms

Services

Router: Pages/Components

Communication between backend and frontend (Http)

Organizing Project: Features Modules/Pages/Components

Login/Register Pages/Components

Guards

Interceptors

Angular Workshop Part II - State Management: NgRX

Link to the repository

5 of 67

Encuesta Angular

  1. ¿Angular? ¿Eso qué es? ¿Se come?

  • Me suena, pero no la he usado nunca...

  • He trabajado con él, y mola mucho.

  • ¿Que si sé Angular? Por favor, podría impartir el taller yo

6 of 67

Angular is a development platform, built on TypeScript. As a platform, Angular includes:

    • A component-based framework for building scalable web applications
    • A collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more
    • A suite of developer tools to help you develop, build, test, and update your code

What is Angular?

7 of 67

Single Page Application (SPA)

  • A SPA is a web application that interacts with the user by dynamically rewriting the current web page with new data from the web server, instead of the default method of a web browser loading entire new pages.
  • In a SPA, a page refresh never occurs; instead, all necessary HTML, JavaScript, and CSS code is either retrieved by the browser.
  • This pattern can significantly improve your application's user experience.

8 of 67

Angular CLI

8

  • The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell.
  • Install the CLI using the npm package manager:

npm install -g @angular/cli

9 of 67

Angular – Standalone Code Structure

ng new workshop-fundamentals --standalone

This command will create a new directory with the boilerplate project and install all required dependencies – thousands of files in the node_modules directory of your project

Key files:

  • app.config.ts - root configuration
  • app.component.ts – root component

Project dependencies

Top-level components

App bootstrap

Root configuration

10 of 67

Angular – How does it work

10

  • Angular follows component-based architecture, where a large application is broken (decoupled) into functional and logical components
  • These components are reusable hence can be used in any other part of the application
  • These components are independent hence can be tested independently; this architecture makes Angular code highly testable

11 of 67

Angular Building Blocks

  • The main building blocks of Angular are:
    • Modules
    • Standalone Components
    • Templates
    • Metadata
    • Services
    • Data binding
    • Directives
    • Interceptors
    • Guards
    • Dependency Injection

12 of 67

Standalone Component

13 of 67

Standalone Components (01-single-component)

14 of 67

Angular - Standalone Components

  • The component is the basic building block of Angular
  • Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed in a target environment

15 of 67

Angular – Create New Component

  • Use the Angular CLI to generate a component and the associated files

ng g component components/hero-item

16 of 67

Angular – Component Details

  • The HeroItemComponent is generated with the template, metadata and the component class

Component Class

Metadata

hero-item.component.ts

Component decorator

Imports Modules and Standalone Components

Template

Styles

17 of 67

Angular HeroItem – Component Class

18 of 67

Angular HeroItem – Template

19 of 67

Angular HeroItem – Load component

  • We want to load our new HeroItemComponent so the root component (app.component.ts) must know about it so we import it and add the HeroItemComponent in the declarations array in app.component.ts

app.component.ts

app.component.html

20 of 67

Angular – Standalone Component

ng serve

  • With “ng serve” running, you can update your code and it will automatically compile and update when you save your files.

21 of 67

Angular - Standalone Components

  • TODO 100 (app.component.html) Incluir el elemento <app-hero-item>
  • TODO 101 (hero-item.ts): Crear isHeroVillain el cual comprueba si el alignment de un héroe es "bad"
  • TODO 102 (hero-item.ts)
    • Comprueba si la habilidad (powerstat) es menor que 100 y le añade una unidad.
    • Comprueba si la habilidad (powerstat) es mayor que 0 y le resta una unidad.
  • TODO 103 (hero-item.html) Muestra el nombre del héroe
  • TODO 104 (hero-item.html) Muestra la inteligencia
  • TODO 105 (hero-item.html) Crea un button con el símbolo +/- e invoca a los métodos decrementPowerStats o incrementPowerStat de la habilidad intelligence. Los botones estarán deshabilitados para restar cuando la intelligence sea 0 y estarán deshabilitados para sumar cuando la intelligence sea 100.
  • TODO 106 (hero-item.html) Igual que TODO 104 y TODO 105 pero para speed, strength, durability, power, combat

22 of 67

Angular HeroItem – *ngFor | pipe

23 of 67

Angular - Standalone Components

  • TODO 107 (hero-item.html)
    • Itera usando *ngFor las habilidades (powerstat) de un héroe, al ser las habilidades un objeto transformalas a key-value usando la pipe “keyvalue”.
    • Utiliza la pipe “titlecase” para que el texto de la habilidad y que comience por mayúsculas

24 of 67

Communication between Components (@Input/@Output)

25 of 67

Communication between components (02-communication)

26 of 67

Angular – @Input/@Output

  • A common pattern in Angular is sharing data between a parent component and one or more child components.
  • Implement this pattern with the @Input() and @Output() decorators.

27 of 67

Angular – @Input/@Output

27

ng g component components/hero-list

28 of 67

Angular - Communication Between Components (@Input/@Output)

  • TODO 200 (app.component.html) Incluir el elemento <app-hero-item>
  • TODO 201 (hero-list.html) Genere tantos componentes app-hero-item como "heroes" hay en el array "heroes", enviar al componente "app-hero-item" cada objeto hero en
  • el input denominado "hero", además configurar el evento de output denominado "powerstatsChange" que invoque al método onPowerstatsChange que recibe el héroe emitido por el componente app-hero-item
  • TODO 202 (hero-item.ts)
    • Crea un atributo hero del tipo Hero, que sea recibido por el componente padre a través del decorador @Input, y que este campo sea requerido.
    • Crea un evento de salida denominado powerstatsChange que emita objetos del tipo HeroPowerstatsChange
  • TODO 203 (hero-item.ts) Emite un objeto del tipo HeroPowerStatsChange que esté compuesto por los siguientes datos: { hero: this.hero, powerstat, value: -1 }
  • TODO 204 (hero-item.ts) Emite un objeto del tipo HeroPowerStatsChange que esté compuesto por los siguientes datos: { hero: this.hero, powerstat, value: 1 }

29 of 67

Reactive Forms

30 of 67

Reactive Forms (03.01-form-new)

31 of 67

Angular – Reactive and Template-Driven Forms

  • Angular provides two different approaches to handling user input through forms: reactive and template-driven.
    • Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.

REACTIVE

TEMPLATE-DRIVEN

Setup of form model

Explicit, created in component class

Implicit, created by directives

Data model

Structured and immutable

Unstructured and mutable

Data flow

Synchronous

Asynchronous

Form validation

Functions

Directives

32 of 67

Angular – Reactive and Template-Driven Forms

  • Both reactive and template-driven forms are built on the following base classes.

BASE CLASSES

DETAILS

FormControl

Tracks the value and validation status of an individual form control

FormGroup

Tracks the same values and status for a collection of form control

FormArray

Tracks the same values ad status for an array of form controls

ControlValueAccessor

Creates a bridge between Angular FormControl instances and built-in DOM elements

33 of 67

Angular – Reactive Forms

34 of 67

Angular – Reactive Forms - FormBuilder

35 of 67

Angular - Reactive Forms

  • TODO 301 (hero.new.component.ts) Inyecta el servicio FormBuilder en un atributo llamado formBuilder que sea privado y de solo lectura
  • TODO 302 (hero.new.component.ts) Crea un atributo denominado heroForm que sea del tipo FormGroup que inicialmente se cree usando formBuilder, con los controles descritos en el código.
  • TODO 303 (hero.new.component.html) Agregar a la etiqueta form, que cuando sea enviado (ngSubmit) se invoque el método addHero, y que el formGroup asociado sea el atributo heroForm.
  • TODO 304 (hero.new.component.html) Agregar el formControlName del input al controlador name
  • TODO 305 (hero.new.component.html) Agregar el formGroupName powerstats al elemento DIV y los formControlName de las diferentes habilidades a los elementos input
  • TODO 306 (hero.new.component.html) Agregar el formControlName a image y alignment

36 of 67

Angular – Form Control States (03.02-form-new-error)

37 of 67

Angular – Form Control States

  • Angular form control states describe the state of a form control in Angular forms.

STATE

DETAILS

CSS-Class

Pristine

The user has not modified the form control

.ng-pristine

Dirty

The user has modified the form control

.ng-dirty

Touched

The user has interacted with the form control, e.g., by clicking or focusing on it.

.ng-touched

Untouched

The form control has not been interacted with by the user

.ng-untouched

Valid

The form control’s value meets the validation rules defined in the application

.ng-valid

Invalid

The form control’s value does not meet the validation rules defined in the application

.ng-invalid

38 of 67

Angular – Form Control States

  • Angular form control states describe the state of a form control in Angular forms.

39 of 67

Angular – Form Control States

40 of 67

Angular – Form Control States

  • TODO 311 (hero.new.component.html) Agrega el div con class error solo si el formControlName name ha sido dirty y es invalido
  • TODO 312 (hero.new.component.html) Agrega un div si el error del controlador name es requerido
  • TODO 313 (hero.new.component.html) Agrega un div si el error del controlador name es heroNameValid
  • TODO 314 (hero.new.component.html) Agrega el div con class error solo si el formControlName name ha sido dirty y está invalido
  • TODO 315 (hero.new.component.html) Agrega un div si el error del controlador name es requerido
  • TODO 316 (hero.new.component.html) Agrega un div si el error del controlador name es heroNameValid

41 of 67

Services

42 of 67

Angular – Services (04.01-services)

  • Service is a broad category encompassing any value, function, or feature that an application needs. A service is typically a class with a narrow, well-defined purpose.
  • A component should use services for tasks that don't involve the view.
  • Services are good for tasks such as fetching data from the server, validating user input, or logging directly to the console.

43 of 67

Angular – Create Service

ng g service shared/services/hero

  • Use the Angular CLI to generate a service for a hero service

44 of 67

Angular – Service Details

@Injectable() decorator to provide the metadata that allows Angular to inject it into a component as a dependency

The hero service is injected

into the App component

45 of 67

Angular – Services

  • TODO 401 (app.component.ts) Injecta el servicio HeroService en una variable llamada heroService privada y de solo lectura.
  • TODO 402 (app.component.ts) Almacena en la variable heroes, el resultado de la invocación del método findAll() del servicio HeroService
  • TODO 403 (app.component.ts) Invoca al método add del servicio HeroService

46 of 67

Router

47 of 67

Angular – Router (05.01-router)

48 of 67

Angular – Router

  • In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page.

  • As users perform application tasks, they need to move between the different views that you have defined.

  • The Router enables navigation by interpreting a browser URL as an instruction to change the view.

49 of 67

Angular – Router

50 of 67

Angular – Router

Each route has 2 properties:

  • path – String that matches URL in browser. Maps to a component
  • component – the component the router should created when navigating to this route

51 of 67

Angular – Router

Each route has 2 properties:

  • path – String that matches URL in browser. Maps to a component
  • component – the component the router should created when navigating to this route

52 of 67

Angular - Router

  • TODO 501 (app.config.ts) Configura el router
  • TODO 502 (app.router.ts) Configurar rutas de heroes
  • TODO 503 (hero-new.component.ts) Navega hasta la página /home
  • TODO 504 (header.component.ts) Configura la navegación entre páginas y activa el routerLinkActive con la clase text-blue-700

53 of 67

Angular – Router (05.02-router-params)

54 of 67

Angular – Router

Each route has 2 properties:

  • path – String that matches URL in browser. Maps to a component
  • component – the component the router should created when navigating to this route

55 of 67

Angular – Router

Each route has 2 properties:

  • path – String that matches URL in browser. Maps to a component
  • component – the component the router should created when navigating to this route

56 of 67

Angular - Router Params

  • TODO 505 (app.routes.ts/hero.resolver) Crea y utiliza un ResolveFn para las rutas que hacen uso del :id del hero.
  • TODO 506 (hero-detail.component.ts/hero-update.component.ts) Crea un observable (hero$) que obtenga el héroe del ActivatedRoute

57 of 67

Communication between client and backend (Http)

58 of 67

Angular – HTTP (06.01-http)

59 of 67

Angular - HTTP

  • Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services. Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http.
  • HttpClient works with Observables

60 of 67

Angular - Http - Observables

  • Angular's HttpClient returns observables from HTTP method calls. For instance, http.get('/api') returns an observable. This provides several advantages over promise-based HTTP APIs:
    • Observables do not mutate the server response (as can occur through chained .then() calls on promises). Instead, you can use a series of operators to transform values as needed.
    • HTTP requests are cancellable through the unsubscribe() method
    • Requests can be configured to get progress event updates
    • Failed requests can be retried easily

61 of 67

Angular - Http - Observables

  • Consider creating an Observable service which will process requests for your store.
  • Your components would subscribe to the service to for processing requests.
  • The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted.

Component (Observer)

Component (Observer)

Service (Observable)

Back-end

e-store (in-memory)

e-store (store on disk)

HTTP Requests

Response

Routing

62 of 67

Angular - Http - Observables

  • In this example, we create a simple Observable that publishes a list of items that are subscribed to by an Observer

Observable object

Using Chrome’s developer tools, we can see our message logged to the console when the button is clicked

63 of 67

Angular - Http - Observables

  • Observables are declarative—that is, you define a function for publishing

values, but it is not executed until an observer (consumer) subscribes to it

  • The subscribed consumer then receives notifications until the function completes, or until they unsubscribe

Observable (publisher)

Observer (consumer)

[data]

[data]

[data]

subscribes

64 of 67

Angular - HTTP - Observables

Observable (publisher)

  • The Observer has three handles to use the data that it receives:
    • next - Required. A handler for each delivered value that’s called zero or more times after execution starts
    • error - Optional. A handler for an error notification. An error halts execution of the observable instance
    • complete - Optional. A handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.

Observer (consumer)

subscribe

next

error

complete

listen

65 of 67

Angular - Http - Observables

  • In this example, we create a simple Observable that publishes a list of items that are subscribed to by an Observer

66 of 67

Angular - HTTP

  • TODO 601 (hero.service.ts) Adaptar hero.service usando httpClient
  • TODO 602 (hero-new.component.ts) Agrega un nuevo hero, si todo va correcto navega a la página /home en caso contrario muestra el error
  • TODO 603 (hero-update.component.ts) Actualiza un nuevo hero, si todo va correcto navega a la página /home en caso contrario muestra el error.

67 of 67

THANK YOU!

Link to the channel

Carlos Caballero

@Caballerog

@carlillo