how to get selected value of dropdown in reactive form

对着背影说爱祢 提交于 2019-12-13 03:19:31

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/48517602/how-to-get-selected-value-of-dropdown-in-reactive-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!