Angular 5 Reactive Forms - 单选按钮组

时间:2018-03-02 22:23:18

标签: angular angular5 angular-reactive-forms

我有2个单选按钮,我使用了被动表单,我在组件中添加了表单控件。我面临的问题是name属性必须与formControlName相同。当我将name属性设置为相同时,我只能选择1个单选按钮 - 永远不能取消选择并选择另一个。只允许我选择同一个。

this.genderControl = new FormControl("", Validators.required);

然后添加到我的表单组

genderControl: this.genderControl,

我的HTML:

<div class="radio-inline">
  <input id="gender" type="radio" name="genderControl" formControlName="genderControl" />
  <label class="radio-label"> Male</label>
  <input id="gender" type="radio" name="genderControl" formControlName="genderControl" />
  <label class="radio-label">Female</label>
</div>

表单组

    this.personalInfo = new FormGroup({
  searchControl: this.searchControl,
  titleControl: this.titleControl,
  firstNameControl: this.firstNameControl,
  middleNameControl: this.middleNameControl,
  lastNameControl: this.lastNameControl,
  birthdayControl: this.birthdayControl,
  genderControl: this.genderControl,
  phoneControl: this.phoneControl,
  taxCanadaControl: this.taxCanadaControl,
  provinceControl: this.provinceControl,
  countryControl: this.countryControl,
  taxCountryControl: this.taxCountryControl,

  creditControl: this.creditControl
});

2 个答案:

答案 0 :(得分:35)

我尝试了你的代码,你没有为formControlName分配/绑定一个值。

在HTML文件中:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

在TS文件中:

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

请确保正确使用“无效”表单:[formGroup]="form"并且您不需要名称属性。

在我的样本中。 span标记中的单词malefemale是单选按钮上显示的值,MaleFemale值绑定到formControlName

查看截图: enter image description here

缩短时间:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

希望有所帮助:)

答案 1 :(得分:2)

如果要导出usg布尔值true False,则需要在值周围添加“ []”

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>