Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...