如何以反应形式获取下拉列表的选定值

2024-01-03

我正在尝试获取要在反应式表单提交时发送的更改事件下拉列表的选定值。根据来自的答案,我有一个非常相似的无线电工作场景如何以反应形式获取无线电的选定值 https://stackoverflow.com/questions/48471846/how-to-get-selected-value-of-radio-in-reactive-form?answertab=votes#tab-top

这是下拉菜单的代码

<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>

当从下拉列表中更改所选选项时,我无法将答案作为表单控件传递给 updateSelection。任何帮助是极大的赞赏。

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


与上一个问题非常相似,我们迭代数组中的表单控件,最初将所有设置为false,然后将所选选项转为true。所以模板让我们通过$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>

在我们提到的组件中迭代表单控件并将所有设置为false。的价值$event.target.value将是字符串值,例如Choice 1。然后,我们搜索具有该值的表单控件,然后为该特定表单组设置布尔值:

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)
}

你的分叉堆栈闪电战 https://stackblitz.com/edit/angular-v2yhbv?file=app%2Fapp.component.ts

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以反应形式获取下拉列表的选定值 的相关文章

随机推荐