Skip to main content

Overview

The AutorFormComponent provides a form interface for administrators to create new authors or edit existing author information. It handles author name and optional photo URL.

Component Metadata

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

Properties

autor

The author object being created or edited. Initialized with default values:
  • id: Set to 0 for new authors
  • nombre: Empty string for author name
  • urlFoto: Empty string for optional photo URL

isEditing

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

Injected Services

  • AutorService - Author 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
    • Loads the author data by calling cargarAutor()
  3. If no id:
    • Sets isEditing to false (create mode)

Methods

cargarAutor

Loads a specific author for editing:
  1. Calls AutorService.getById(id)
  2. Populates the autor object with the response data
  3. Ensures urlFoto is an empty string if null/undefined
  4. Logs errors to console if any occur
Parameters:
  • id - The numeric ID of the author 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 es obligatorio” if validation fails
Update Mode (isEditing = true):
  1. Calls AutorService.update() with the full autor object
  2. On success:
    • Shows alert “Autor actualizado correctamente”
    • Navigates to /autores
  3. On error:
    • Logs error to console
    • Shows alert “Error al actualizar el autor.”
Create Mode (isEditing = false):
  1. Creates autorParaGuardar object with only nombre and urlFoto (excludes id)
  2. Calls AutorService.create() with the data
  3. On success:
    • Shows alert “Autor creado correctamente”
    • Navigates to /autores
  4. On error:
    • Logs error to console
    • Shows alert “Error al crear el autor. Revisa la consola.”

Full Source Code

  • Autor - Author data structure