Angular 5反应形式-单选按钮组 [英] Angular 5 Reactive Forms - Radio Button Group

查看:42
本文介绍了Angular 5反应形式-单选按钮组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 radio buttons, I'm using reactive forms and I have added the form controls within my component. The issue I am facing is that the name attribute has to be the same as the formControlName. When I set the name attribute as the same, I can only select 1 radio button -- can never unselect and select the other one. Only allows me to select the same one.

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

,然后添加到我的表单组

and then added to my Form Group

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
});

推荐答案

我尝试了您的代码,但没有为formControlName分配/绑定值.

I tried your code, you didn't assign/bind a value to your 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",并且不需要name属性.

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

在我的示例中. span标签中的单词malefemale是沿单选按钮显示的值,并且MaleFemale值绑定到formControlName

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

查看屏幕截图:

使其更简短:

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

希望它会有所帮助:)

这篇关于Angular 5反应形式-单选按钮组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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