Angular 4响应式表单下拉框选中值获取问题
解决Angular ReactiveForms单选下拉框提交整个数组的问题
这问题我之前也碰到过,核心原因是你把单选select控件和FormArray绑定错了!FormArray是用来管理多个独立表单控件的(比如一组多选框、多个输入框),但单选select只需要一个单独的FormControl来存储用户选中的单个值,你现在的写法让Angular把整个FormArray的内容当成了select的值,所以提交时才会输出完整数组。
下面是修正后的代码:
1. 修改组件.ts文件
我们不再用FormArray来存选项列表,而是把选项作为普通数组,新增一个FormControl专门存储选中值:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponentComponent implements OnInit { myForm: FormGroup; // 普通数组用来渲染下拉选项,不需要绑定到表单控件 dataTypes = ["A", "B", "C"]; // 用FormControl存储用户选中的值,可设置默认选中项 selectedDataType: FormControl; ngOnInit() { // 默认选中第一个选项"A" this.selectedDataType = new FormControl("A"); this.myForm = new FormGroup({ // 将选中值控件加入表单组 selectedDataType: this.selectedDataType }); } onSubmit() { console.log(this.myForm.value); // 提交后控制台会输出类似:{ selectedDataType: "B" }(用户选中的对应值) } }
2. 修改HTML模板
把select的绑定从formArrayName改成formControlName,直接关联存储选中值的FormControl:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()"> <select name="datatypes" id="datatypes" formControlName="selectedDataType" > <option *ngFor="let dataType of dataTypes; let dataIndex=index" [ngValue]="dataType" > {{ dataType }} </option> </select> <button type="submit">Submit</button> </form>
额外说明
如果你需要存储选中项的索引而非值,只需要做两处小修改:
- 在ts里把FormControl的默认值改成
0(对应第一个选项的索引) - 在HTML里把
[ngValue]="dataType"改成[ngValue]="dataIndex"
这样提交后就会输出选中项的索引值啦。
内容的提问来源于stack exchange,提问作者Shiv Kumar
相关产品推荐
相关产品推荐

