How to bind to radio buttons in angular2 beta 6

2020-02-05 06:40发布

问题:

How does one achieve radio button binding in beta 6?

I found a great plnkr for beta 0 (see http://plnkr.co/edit/aggee6An1iHfwsqGoE3q?p=preview), but when I try to update it to beta 6 it breaks horribly (see http://plnkr.co/edit/voU933?p=preview).

I took a look at the commit that added built-in support for radio options (see https://github.com/angular/angular/commit/e725542), which gives this example

@Component({
  template: `
    <input type="radio" name="food" [(ngModel)]="foodChicken">
    <input type="radio" name="food" [(ngModel)]="foodFish">
  `
})
class FoodCmp {
  foodChicken = new RadioButtonState(true, "chicken");
  foodFish = new RadioButtonState(false, "fish");
}

but my attempts to make that work have so far ended up quite like my failed plnkr.

回答1:

Update

Radio is working fine in RC.4 and the new forms module. See for example the Plunker in https://stackoverflow.com/a/38590919/217408

Original

Several issues.

Using <script src="https://code.angularjs.org/2.0.0-beta.7/angular2.min.js"></script> caused an exception. I got rid of it by removing `min.?

The radio binds the value {checked: true} instead of value. This is obviously a bug and probably the same as these

  • Radio button data binding and form validation not working
  • Cannot select multiple radio buttons in same control group (fixed)
  • input type=radio not handled correctly by ng-model (fixed)
  • https://github.com/angular/angular/issues/7642

I got it working with an ugly workaround. See https://plnkr.co/edit/988PSJKXCfrUXfLOGgyg?p=preview

    <input type="radio" [ngModel]="{checked: model.sex == 'male'}" (ngModelChange)="model.sex='male'"  name="sex" value="male">Male<br>
    <input type="radio" [ngModel]="{checked: model.sex == 'female'}"  (ngModelChange)="model.sex='female'" name="sex" value="female">Female


回答2:

For anyone reading this, forms have changed and so have radio buttons in recents release ( RC 3 ), no need for tricks now :)

This PR adds the ability for radio buttons to share a FormControl instance. This means you no longer need to create a RadioButtonState to manage radio buttons.

Before:

<form #f="ngForm">
   <input type="radio" name="food" [(ngModel)]="foodChicken">
    <input type="radio" name="food" [(ngModel)]="foodFish">
</form>

{{ f. value | json }}      // { foodChicken: {value: 'chicken', checked: false}, foodFish: {value: 'fish', checked: true} }
class MyComp {
   foodChicken = new RadioButtonState(false, 'chicken');
   foodFish = new RadioButtonState(true, 'fish');
}

After:

<form #f="ngForm">
   <input type="radio" name="food" [(ngModel)]="food" value="chicken">
   <input type="radio" name="food" [(ngModel)]="food" value="fish">
</form>

{{ f. value | json }}      // { food: 'fish' }
class MyComp {
   food = 'fish';
}

see https://github.com/angular/angular/pull/9228



回答3:

Maybe you can get rid of the (ngModelChange) and hard coding input values twice using (change) event:

<input type="radio" [ngModel]="{checked: model.sex == 'male'}" (change)="model.sex=$event.target.value"  name="sex" value="male">Male<br>
<input type="radio" [ngModel]="{checked: model.sex == 'female'}" (change)="model.sex=$event.target.value" name="sex" value="female">Female

Updated plnkr.co demo: https://plnkr.co/edit/NiN83eCzMD3V6oe88Obg?p=preview



回答4:

I've created a version by using just a click event on the elements loaded and passing the value of the selection into the function "getSelection" and updating the model.

In your template:

<ul> <li *ngFor="let p of price"><input type="radio" name="price" (click)="getValue(price.value)" value="{{p}}" #price> {{p}} </li> </ul>

Your class:

export class App {

  price:string;

  price = ["1000", "2000", "3000"];

  constructor() {   }

  model = new SomeData(this.price);

  getValue(price){
    this.model.price = price;
  }
}

See example: https://plnkr.co/edit/2Muje8yvWZVL9OXqG0pW?p=info



回答5:

  <div class="col-lg-4">
            <div class="form-group">
              <legend class="col-form-legend">Sexo</legend>
              <label class="custom-control custom-radio">
                <input value="macho" [(ngModel)]="pet.sexo" name="pet.sexo1" id="radio1"  type="radio" class="custom-control-input">
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">Macho</span>
              </label>
              <label class="custom-control custom-radio">
                <input  value="femea"  [(ngModel)]="pet.sexo" name="pet.sexo2" id="radio2"  type="radio" class="custom-control-input">
                <span class="custom-control-indicator"></span>
                <span  class="custom-control-description">Fêmea</span>
              </label>
            </div>
          </div>