Skip to main content

Overview

The LibroFormComponent provides a form interface for administrators to create new books or edit existing ones. It handles book details, genre selection, author assignment, and cover image management.

Component Metadata

Selector: app-libro-form Imports:
  • CommonModule - Angular common directives
  • FormsModule - Template-driven forms support
  • RouterLink - Router navigation
Template: ./libro-form.html

Properties

listaAutores

Array of all available authors for selection in the multi-select dropdown.

listaGeneros

Array of all available genres for selection in the genre dropdown.

selectedGeneroId

Holds the ID of the selected genre. Used for binding to the select element.

selectedAutoresIds

Array of selected author IDs. A book can have multiple authors.

libro

The book object being created or edited. Initialized with default values.

isEditing

Indicates whether the form is in edit mode (true) or create mode (false).

Injected Services

  • LibroService - Book CRUD operations
  • AutorService - Fetches author data
  • GeneroService - Fetches genre data
  • Router - Navigation after save
  • ActivatedRoute - Reads route parameters to detect edit mode

Lifecycle Hooks

ngOnInit

  1. Loads the lists of authors and genres
  2. Checks if an id parameter exists in the route
  3. If id exists, sets isEditing to true and loads the book data

Methods

cargarListas

Fetches all genres and authors from their respective services:
  • Calls GeneroService.getAll() and populates listaGeneros
  • Calls AutorService.getAll() and populates listaAutores
  • Logs errors to console if any occur

cargarLibro

Loads a specific book for editing:
  1. Calls LibroService.getById(id)
  2. Populates the libro object with the response data
  3. Maps the book’s genre to selectedGeneroId
  4. Maps the book’s authors to selectedAutoresIds array
Parameters:
  • id - The numeric ID of the book to load

onSubmit

Handles form submission for both create and update operations: Validation:
  1. Checks that titulo is not empty
  2. Validates that a genre is selected
  3. Ensures at least one author is selected
Data Preparation:
  • Creates a libroParaEnviar object with:
    • All libro properties
    • Genre as { id: selectedGeneroId }
    • Authors as array of { id } objects
  • Removes the id property when creating a new book
API Call:
  • If editing: Calls LibroService.update() with libro ID and data
  • If creating: Calls LibroService.create() with data (without ID)
  • On success: Shows success alert and navigates to /libros
  • On error: Shows error alert and logs to console

Template Features

Form Fields

Full Source Code

  • Libro - Book data structure
  • Autor - Author data structure
  • Genero - Genre data structure