我具有以下形式,其中充满了多个选择输入
<form [formGroup]="searchForm" (ngSubmit)="onSubmit(searchForm.value)">
<div class="col-md-2" *ngFor="let filter of this.filters; index as i">
<div class="form-group">
<select formArrayName="filters" size="5" class="form-control" (change)="onSelectChange($event)">
<option [ngValue]="null" value="-1" disabled class="first-option-item">{{ filter.name }}</option>
<option
*ngFor="let filterValue of this.filterValues[i].items"
[ngValue]="filterValue">
{{ filterValue.name }}
</option>
</select>
</div>
</div>
</form>
活动表单初始化:
this.searchForm = this.formBuilder.group({
searchString: ['', Validators.required],
filters: this.formBuilder.array([ ])
});
但是,当我提交表单时,过滤器数组上没有任何值
此外,当我在(更改)方法上登录e.target.value
时,只会得到所选的选项值。我想访问完整的对象,即{ id: 1, name: 'first_filter' }
。我不需要完整的对象,以便以某种方式将其返回给FormGroup吗?
答案 0 :(得分:0)
您正在构建表单中的选择数组。提交表单时,未设置选择值。
绑定到表单数组时,将数组绑定到formArrayName
,并将数组中的每个控件绑定到[formControlName]="i"
。
将formArrayName="filters"
移动到更高的级别,然后将[formControlName]="i"
添加到选择中。这会将第i
个选择绑定到表单数组中的第i
个控件。
出于我的示例目的,我还修改了您的[ngValue]="filterValue"
以使用filterValue.name
。
<form [formGroup]="searchForm" (ngSubmit)="onSubmit()">
<div class="col-md-2" *ngFor="let filter of this.filters; index as i"
formArrayName="filters">
<div class="form-group">
<select [formControlName]="i" size="5" class="form-control" (change)="onSelectChange($event)">
<option [ngValue]="null" value="-1" disabled class="first-option-item">{{ filter.name }}</option>
<option
*ngFor="let filterValue of this.filterValues[i].items"
[ngValue]="filterValue.name">
{{ filterValue.name }}
</option>
</select>
</div>
</div>
<button>Submit</button>
</form>