Tim Heinze
Tim Heinze

Reputation: 9

Angular can't retrieve selected option from a selection

So I have a module form which appears as a pop-up. In this form, you can provide Data which is needed to create a new object of a class. One field you can fill with data is a selection where you can select the ventilation zone which is used for the new room object. The problem is that I can not access the chosen option. I couldn't find any solution on google or StackOverflow.

component.html:

<ng-.template #content let-modal>
  <div class='modal-header'>
  ...
  </div>
  <div class="modal-body>
     <form #f="ngForm" (ngSubmit)="onSubmitRoom(f, selectedBuildingUnit)" novalidate>
       <div class="formGroup">
         <label for="ventilationZoneOfRoom">Ventilation zone</label>
         <div class="input-group">
           <select id="ventilationZoneOfRoom" name="ventilationZoneOfRoom" class="form-control" ngModal>
             <option *ngFor="let ventilationzone of building.ventilationzones"
                     [ngValue]="ventilationzone">
               {{ventilationzone.name}}
             </option>
           </select>
         </div>
       </div>
      ...
   </form

component.ts:

onSubmitRoom(f: NgForm, buildingunit: Buildingunit) {
    let room = new Room(
      "",
      f.value.someValue;
      ...
    );
    room.ventilationzone = f.value.ventilationZonOfRoom
    console.log(f.value)
    console.log(f.value.ventilationZoneOfRoom)
    room.ventilationzone?.rooms.push(room)

Every input from this form can be retrieved instead of the selected option. So a standard input can be retrieved via the defined id.

When I try to get f.value.ventilationZoneOfRoom I only get undefined. As well as that when I print f.value the parameter ventilationZoneOfRoom doesn't even exist.

I have no clue why it is like this but I hope one of you can help me with this. If you need any further information I will provide that

Upvotes: 0

Views: 327

Answers (1)

Manuel Tom&#225;s
Manuel Tom&#225;s

Reputation: 570

I think the problem is that you are using [ngValue]="ventilationzone" and not value={{ventilationzone}}.

Furthermore, I don't know if it is necessary, but normally when I implement forms like this, I put a formControlName on each field. So it would be something like:

<select id="ventilationZoneOfRoom" name="ventilationZoneOfRoom" class="form-control" formControlName="ventilationZoneOfRoom">
      <option *ngFor="let ventilationzone of building.ventilationzones" value={{ventilationzone}}>
               {{ventilationzone.name}}
      </option>
</select>

Upvotes: 1

Related Questions