Angular ReactiveForms:生成一个复选框值数组? [英] Angular ReactiveForms: Producing an array of checkbox values?
问题描述
给定绑定到相同 formControlName
的复选框列表,如何生成绑定到 formControl $ c的复选框值数组$ c>,而不是简单地
true
/ false
?
Given a list of checkboxes bound to the same formControlName
, how can I produce an array of checkbox values bound to the formControl
, rather than simply true
/false
?
示例:
<form [formGroup]="checkboxGroup">
<input type="checkbox" id="checkbox-1" value="value-1" formControlName="myValues" />
<input type="checkbox" id="checkbox-2" value="value-2" formControlName="myValues" />
<input type="checkbox" id="checkbox-3" value="value-2" formControlName="myValues" />
</form>
checkboxGroup.controls ['myValues']。value
目前产生:
checkboxGroup.controls['myValues'].value
currently produces:
true or false
我希望它生成什么:
['value-1', 'value-2', ...]
推荐答案
这是一个使用 FormArray的好地方
https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html
首先,我们将使用 FormBuilder
构建我们的控件数组,或者新建一个 FormArray
To start we'll build up our array of controls either with a FormBuilder
or newing up a FormArray
FormBuilder
this.checkboxGroup = _fb.group({
myValues: _fb.array([true, false, true])
});
new FormArray
let checkboxArray = new FormArray([
new FormControl(true),
new FormControl(false),
new FormControl(true)]);
this.checkboxGroup = _fb.group({
myValues: checkboxArray
});
很容易做到,但接下来我们要更改模板并让模板引擎处理我们如何绑定到我们的控件:
Easy enough to do, but then we're going to change our template and let the templating engine handle how we bind to our controls:
template.html
<form [formGroup]="checkboxGroup">
<input *ngFor="let control of checkboxGroup.controls['myValues'].controls"
type="checkbox" id="checkbox-1" value="value-1" [formControl]="control" />
</form>
这里我们迭代我们的 FormControls
在我们的 myValues
FormArray
中,对于每个控件我们都绑定 [formControl]
到该控件而不是 FormArray
控件和< div> {{checkboxGroup.controls ['myValues']。 value}}< / div>
生成 true,false,true
,同时还可以减少模板语法的手动。
Here we're iterating over our set of FormControls
in our myValues
FormArray
and for each control we're binding [formControl]
to that control instead of to the FormArray
control and <div>{{checkboxGroup.controls['myValues'].value}}</div>
produces true,false,true
while also making your template syntax a little less manual.
您可以使用此示例: http://plnkr.co / edit / a9OdMAq2YIwQFo7gixbj?p =预览来探讨
You can use this example: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview to poke around
这篇关于Angular ReactiveForms:生成一个复选框值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!