Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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'"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...