简体   繁体   中英

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.

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
});

Angular.js (1.x) had ng-true-value and ng-false-value, which was convenient to avoid conversions between the web form and an inflexible backend:

<input type="checkbox" ng-model="vv[name]" ng-true-value="'1'" ng-false-value="'0'"/>

Angular 2+ has the banana-in-a-box notation to bind directly to the model, but that data type must be boolean to work with a checkbox:

<input type="checkbox" [(ngModel)]="vv[name]"/>

If you really can't use booleans, the [checked] and (change) notation is a workable substitute (in this case, 1 is true, 0 is false):

<input type="checkbox" [checked]="vv[name]==='1'"                                            
    (change)="vv[name]=$event.target.checked?'1':'0'"/>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM