Skip to main content

Overview

The GeneroFormComponent provides a simple form interface for administrators to create new literary genres or edit existing genre names.

Component Metadata

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

Properties

genero

The genre object being created or edited. Initialized with default values:
  • id: Set to 0 for new genres
  • nombre: Empty string for genre name

isEditing

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

Injected Services

  • GeneroService - Genre CRUD operations
  • Router - Navigation after save
  • ActivatedRoute - Reads route parameters to detect edit mode

Lifecycle Hooks

ngOnInit

  1. Checks if an id parameter exists in the route
  2. If id exists:
    • Sets isEditing to true (edit mode)
    • Loads the genre data by calling cargarGenero()
  3. If no id:
    • Sets isEditing to false (create mode)

Methods

cargarGenero

Loads a specific genre for editing:
  1. Calls GeneroService.getById(id)
  2. Populates the genero object with the response data
  3. Logs errors to console if any occur
Parameters:
  • id - The numeric ID of the genre to load

onSubmit

Handles form submission for both create and update operations: Validation:
  • Checks that nombre is not empty (after trimming whitespace)
  • Shows alert “El nombre del género es obligatorio” if validation fails
Update Mode (isEditing = true):
  1. Calls GeneroService.update() with the genre ID and full genero object
  2. On success:
    • Shows alert “Género actualizado correctamente”
    • Navigates to /generos
  3. On error:
    • Logs error to console
    • Shows alert “Error al actualizar el género.”
Create Mode (isEditing = false):
  1. Creates generoParaGuardar object with only nombre (excludes id)
  2. Calls GeneroService.create() with the data
  3. On success:
    • Shows alert “Género creado correctamente”
    • Navigates to /generos
  4. On error:
    • Logs error to console
    • Shows alert “Error al crear el género.”

Full Source Code

  • Genero - Genre data structure