首页 > 解决方案 > 如何确保在 Angular 2+ 的同一表单组下默认未选中单选按钮?

问题描述

数据通过数据库中的数据(Web-API)绑定到单选按钮。我的完整代码如下:

组件.html

        <!-- list of Questions -->
    <div formArrayName="questions">
   <!-- <div *ngFor="let que of Questions; let k=index"> -->
    <div *ngFor="let question of Ques ; let i=index" [formGroupName]="i" >

    <!-- The repeated questions template -->
  <h4>Question #{{i + 1}}</h4>
 <div style="margin-left: 1em;">
   <div class="form-group">
     <label class="center-block">
       <input class="form-control" formControlName="ques" disabled>
     </label>
    </div>


 <div class="form-group radio" *ngFor="let choice of question.choices ">
      <input type="radio"  formControlName="choices"
          class="custom-control-input" [value]="choice">
      <label>{{choice.choiceText}}</label>
    </div> 

组件.ts

export class CheckListFormComponent implements OnInit, OnChanges {

  Ques: Questions[];

  Questions: any = [];

  choices: Choices;


  constructor(private fb: FormBuilder,
          private checklistservice: ChecklistService) { 
    this.CreateForm();

   }

   ngOnInit() {
     this.checklistservice.getQuestions(1).subscribe(res =>{ this.Ques =res;
      this.setquestions(this.Ques)
               }); 

    this.checklistservice.getQuestions(1).subscribe(res =>{ 
      this.Questions = res;
    console.log(this.Questions)
  }); 

   this.Questions.forEach(q => {
   this.choices = q.choices;
     });
                }


    ngOnChanges() {

                  }


              CreateForm() {
      this.CheckListForm = this.fb.group({

     name: ['', Validators.required],
     EmploymentType: ['', Validators.required],
     HRMS: ['', Validators.required],
     CompanyName:'',
    questions: this.fb.array([]) 
                        })
                           }

          get questions(): FormArray {
        return this.CheckListForm.get('questions') as FormArray;
                                     }


  setquestions(questions: Questions[]) {
  const QuestionsFGs = questions.map(questions => this.fb.group(questions));
  const QuestionsFormArray = this.fb.array(QuestionsFGs);
 this.CheckListForm.setControl('questions', QuestionsFormArray);
                                        }


                                  }

在我的表单数组中使用此代码会生成单选按钮,其中一个选项被选中(只有 2 个选项)。我需要设计单选按钮,使两个按钮都保持未选中状态。这样当用户提交表单时,未选中的单选按钮将产生验证错误,因为所有表单字段都是强制性的。如何确保默认情况下不检查任何单选按钮?

标签: angular

解决方案


像往常一样没有回应,所以我将继续回答我自己的问题。

要解决这个问题,您需要在问题数组中为每个问题模型创建新的表单控件。为表单控件设置validation.required。

然后通过表单控件迭代选择模型,默认情况下未选中单选按钮。


推荐阅读