Bind checkbox to value instead of true/false with reactive forms

ⅰ亾dé卋堺 提交于 2019-12-29 08:28:07

问题


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.

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?

The template:

<form [formGroup]="checkboxGroup">
    <input *ngFor="let control of checkboxGroup.controls['myValues'].controls" 
    type="checkbox" id="checkbox-1" value="value-1" [formControl]="control" />
</form>

And the component:

let checkboxArray = new FormArray([
  new FormControl({checked: true, value: "value1"}),
  new FormControl({checked: false, value: "value2"}))]);

this.checkboxGroup = _fb.group({
  myValues: checkboxArray
});

回答1:


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 .



来源:https://stackoverflow.com/questions/41084488/bind-checkbox-to-value-instead-of-true-false-with-reactive-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!