Search code examples
angular-reactive-formsangular4-formsformarrayformgroups

how to get selected value of dropdown in reactive form


I am trying to get the selected value of the dropdown on change event to be sent on reactive form submission. I have a very similar scenario working for radio based on the answer from how to get selected value of radio in reactive form

Here's the code for dropdown

<div class="row" *ngIf="question.controls.type.value === 'dropdown'">
   <div class="col-md-12">
    <div class="form-group__text select">
      <label for="type">{{ question.controls.label.value }}</label>
      <br><br>
      <select name="value" formArrayName="component" (change)="updateSelection(question.controls.component.controls, $event.target)">
        <option
          *ngFor="let answer of question.controls.component.controls; let j = index" [formGroupName]="j"
          [ngValue]="answer?.value?.value">
            {{answer?.value?.value}}
        </option>
      </select>
    </div>
  </div>
 </div>

I am not able to pass the answer as formcontrol to updateSelection on change of a selected option from the dropdown. Any help is greatly appreciated.

https://stackblitz.com/edit/angular-acdcac


Solution

  • Very similarily like previous question, we iterate the form controls in your array, initially set all as false, and then turn the chosen choice as true. So template let's pass $event.target.value:

    <select name="value" formArrayName="component" 
       (change)="updateSelection(question.controls.component.controls, $event.target.value)">
        <option *ngFor="let answer of question.controls.component.controls; let j = index" [formGroupName]="j"
           [ngValue]="answer?.value?.value">
           {{answer?.value?.value}}
      </option>
    </select>
    

    And in the component we as mentioned iterate the form controls and set all as false. The value for $event.target.value will be the string value, for example Choice 1. We then search for the form control that has that value and then set the boolean for that particular formgroup:

    updateSelection(formArr, answer) {
      formArr.forEach(x => {
        x.controls.selectedValue.setValue(false)
      })
      let ctrl = formArr.find(x => x.value.value === answer)
      ctrl.controls.selectedValue.setValue(true)
    }
    

    Your forked StackBlitz