如何以反应形式获得下拉列表的选定值 [英] 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
这是下拉菜单的代码
<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>
在从下拉列表中更改所选选项时,我无法将答案作为formcontrol传递给updateSelection.任何帮助,我们将不胜感激.
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
推荐答案
与上一个问题非常相似,我们迭代数组中的表单控件,最初将所有控件设置为false
,然后将选择的选项设置为true
.因此模板让我们传递$event.target.value
:
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>
在组件中,如上所述,我们对表单控件进行了迭代,并将所有控件都设置为false
. $event.target.value
的值将是字符串值,例如Choice 1
.然后,我们搜索具有该值的表单控件,然后为该特定表单组设置布尔值:
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)
}
您分叉的 StackBlitz
Your forked StackBlitz
这篇关于如何以反应形式获得下拉列表的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!