Angular2反应形式动态单选按钮组

时间:2018-08-17 16:58:13

标签: angular angular-reactive-forms angular-forms

我有一个带有单选按钮作为答案的问题列表。我事先不知道问题或答案的数量,但是每个问题都有其唯一的ID。我正在组件类中为answersid使用吸气剂。

<div class="mb-2">
    <div class="form-check form-check-inline" *ngFor="let answer of answers.controls">
      <input type="radio"
        id="{{id.value}}"
        name="{{id.value}}" <!-- This should be unique for each group -->
        [formControl]="answer.get('selected')"
        [checked]="(answer.get('selected').value == true)"
        class="form-check-input"
      <label class="form-check-label" for="{{id.value}}">
        {{answer.get('text').value}}
      </label>
    </div>
  </div>

组件类方法:

  get answers() {
    return this.questionForm.get('answers') as FormArray;
  }
  get id() {
    return this.questionForm.get('id') as FormControl;
  }

当我选择一个答案时,组中的所有单选按钮都被选中。但是,名称在组之间是唯一的,但在组内共享。我想念什么吗?

2 个答案:

答案 0 :(得分:0)

对于实现反应形式,您不需要使用html attibute 尝试像这样更改代码

 this.SignupForm = new FormGroup({
      'userData': new FormGroup({
          'username':new FormControl(null,[Validators.required]),
          'email':new FormControl(null, 
          [Validators.required,Validators.email]),
      }),
      'gender':new FormControl('female'), //This radio button
      'hobbies':new FormArray([])
    });

检查此示例:https://stackblitz.com/edit/angular-reactive-forms

答案 1 :(得分:0)

您需要绑定输入值并删除选中的

   <input type="radio" value ="answer.get('selected').value"
    id="{{id.value}}"
    name="{{id.value}}" 
    [formControl]="answer.get('selected')"
    class="form-check-input">