0

The goal: Create a booking instance via the Angular frontend

What I've done: I'm setting one of the booking fields "category" with an HTML option input via TypeScript. The field has an object as data type. That object has two fields, id and name.

When I set the category field with the value I get from the option input, it sets the category name with that value, but not the id. How can I set the id field instead of the name field?

Screenshot of debugging:

enter image description here

booking.ts

import {Category} from "./category";

export interface Booking {
  id: number;
  value: number;
  category: Category;
  date: Date;
}

category.ts

export interface Category {
  id: number;
  name: string;
}

option input:

<select type="text" ngModel name="category" class="custom-select" id="category">
   <option selected>wähle...</option>
   <option *ngFor="let category of categories" value="{{category.id}}">{{category.name}} 
   </option>
</select>

Create Booking function:

  public createBooking(addBookingForm: NgForm) {
    this.bookingService.addBooking(addBookingForm.value).subscribe(
      (response: Booking) => {
        console.log(response);
        window.location.reload();
      },
      (error: HttpErrorResponse) => {
        alert(error.message);
      }
    )
  }
lu_lu
  • 133
  • 12
  • "Screenshot of debugging" might help sighted humans, but does nothing for people who have visual impairments, and search engine crawlers don't crawl text in images. Those are two reasons we ask everyone to [please not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Heretic Monkey Aug 11 '22 at 11:53
  • I solved the issue by using ngValue instead of value and posted it as an answer under my question. But yes, the post you mentioned also captures that solution, thank you. @HereticMonkey – lu_lu Aug 11 '22 at 12:02
  • I noticed that you used the same code as the answer provided by Chellappan in your own answer without giving credit to them, yes. The point of duplicates is to keep solutions in one place instead of fractured among several hundred of the same question, making it easier to search and find the answer. See [Why are some questions marked as duplicate?](/help/duplicates) for more. – Heretic Monkey Aug 11 '22 at 12:05
  • He copied my code and added some code (including a function), which I didn't use.. So no, it's not a duplicate, but thank you for keeping track of the post. @HereticMonkey – lu_lu Aug 11 '22 at 12:47

1 Answers1

0

The solution is to use ngValue instead of value and give it the category list item, while the iteration via *ngFor takes place:

<select type="text" ngModel name="category" class="custom-select" id="category">
      <option selected>select...</option>
      <option *ngFor="let category of categories" [ngValue]="category">{{category.name}}</option>
</select>
lu_lu
  • 133
  • 12