使用反应形式将复选框绑定到值,而不是true/false [英] Bind checkbox to value instead of true/false with reactive forms
问题描述
我试图得到一个使用反应式/模型驱动形式的简单示例.我想将复选框数组绑定到值列表,而不是布尔值列表.
I'm trying to get a simple example working using reactive/model driven forms. I want to bind an array of checkboxes to a list of values, and not a list of boolean values.
这个小伙子显示了问题: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=预览绑定到表单的值是布尔值,我希望答案类似于["value1", "value2", etc]
This plunker shows the problem: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview The values bound to the forms are booleans, I'd like the answer to be something like ["value1", "value2", etc]
我有类似的东西,但是我不知道如何获得想要的结果?
I have something like this, but I don't know how to get the result that I want?
模板:
<form [formGroup]="checkboxGroup">
<input *ngFor="let control of checkboxGroup.controls['myValues'].controls"
type="checkbox" id="checkbox-1" value="value-1" [formControl]="control" />
</form>
以及组件:
let checkboxArray = new FormArray([
new FormControl({checked: true, value: "value1"}),
new FormControl({checked: false, value: "value2"}))]);
this.checkboxGroup = _fb.group({
myValues: checkboxArray
});
推荐答案
已选中(true)或未选中(false)复选框值. 一般来说,复选框具有另一个值没有意义,但是如果您仍要这样做,则需要编写自己的复选框值评估器.
A checkbox value is either checked ( true ) or not checked ( false ). Generally speaking, doesn't make sense for a checkbox to have another value but if you want to do this nonetheless , you'd need to write your own Checkbox Value Assessor .
这篇关于使用反应形式将复选框绑定到值,而不是true/false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!