我有两个单选按钮,我使用的是react 式表单,我在我的组件中添加了表单控件.我面临的问题是name属性必须与formControlName相同.当我将name属性设置为相同时,我只能 Select 一个单选按钮——不能取消 Select 并 Select 另一个.只允许我 Select 同一个.

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

推荐答案

我try 了您的代码,但您没有为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]
    });
  }

确保正确使用react 形式:[formGroup]="form",并且不需要name属性.

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

See the screenshot: 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

希望有帮助:)

Angular相关问答推荐

Angular中绑定嵌入标签src属性的问题

RXJS运算符用于combineLatest,不含空值

HttpInterceptorFn在Angular 17中被忽略

元素上的Angular 管道链接不起作用

带区域设置用法的Angular 日期管道

Ngrx Select 器返回部分对象

使用forkJoin和mergeMap的正确方式是什么?

根据最后发出的 observable 创建一个 observable

Angular:如何在根组件中使用 ngx-translate?

Renderer2.appendChild 没有按预期工作?

RxJS - .withLatestFrom 的多个来源

Angular 2: Debounce(ngModelChange)?

Angular 2 - 事件列表

Angular 2 - 什么是Root Scope?

导航到同一条route路由不刷新组件?

Angular 2 中的 OnChanges 和 DoCheck 有什么区别?

没有 ChildrenOutletContexts 的提供者 (injectionError)

angular2 测试,我如何模拟子组件

在 Angular 2 中对 observable 进行单元测试

Angular2:CoreModule 与 SharedModule