Angular2 ReactiveFormsControl:如何绑定单选按钮? [英] Angular2 ReactiveFormsControl: how to bind radio buttons?

查看:101
本文介绍了Angular2 ReactiveFormsControl:如何绑定单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular2的 ReactiveFormsModule 创建一个包含表单的组件。这是我的代码:

I'm using ReactiveFormsModule of Angular2 to create a component that contains a form. Here is my code:

foo.component.ts

constructor(fb: FormBuilder) {
    this.myForm = fb.group({
        'name': ['', Validators.required],
        'surname': ['', Validators.required],
        'gender': []
    });
}

foo.component.html

<div class="two fields">
    <div class="four wide field">
        <label>Name*</label>
        <input type="text" [formControl]="myForm.controls.name"/>
    </div>

    <div class="four wide field">
        <label>Surname*</label>
        <input type="text" [formControl]="myForm.controls.surname"/>
    </div>
</div>

<div class="inline fields">
    <label for="gender">Gender</label>
    <div class="field">
        <div class="ui radio checkbox">
            <input type="radio" name="gender" checked="" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
            <label>Male</label>
        </div>
    </div>
    <div class="field">
        <div class="ui radio checkbox">
            <input type="radio" name="gender" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
            <label>Female</label>
        </div>
    </div>
</div>

我上面发布的代码不起作用:如果我单击两个单选按钮之一,总是选择第二个,但我不能更改。

The code i posted above doesn't work: if i click on one of the two radio buttons it always select the second one and i can't change it.

FormControl 中使用正确的方法是什么收音机(或复选框)?

What is the right way to use FormControl with radio (or checkbox)?

推荐答案

对于除 string 值之外的其他值,您可以使用 [value] 属性,还应将 [checked] 属性用于

For other than string values you may use [value] attribute and also [checked] attribute should be used for initial values.

export enum Gender {
  FEMALE = 1,
  MALE   = 2
}

export class SampleGenderComponent implements OnInit {

  public form: FormGroup;
  public Gender = Gender;

  constructor(fb: FormBuilder) {

    this.form = fb.group({
      gender    : [
        Gender.FEMALE,
        []
      ]
    });
  }
}



<div class="inline fields">
  <label for="gender">Gender</label>
  <div class="field">
    <div class="ui radio checkbox">
      <input type="radio" name="gender" [value]="Gender.MALE" [checked]="form.controls['gender'].value === Gender.MALE">
      <label>Male</label>
    </div>
  </div>
  <div class="field">
    <div class="ui radio checkbox">
      <input type="radio" name="gender" [value]="Gender.FEMALE" [checked]="form.controls['gender'].value === Gender.FEMALE">
      <label>Female</label>
    </div>
  </div>
</div>

这篇关于Angular2 ReactiveFormsControl:如何绑定单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆