数据通过数据库(Web-API)中的数据绑定到单选按钮。我的完整代码如下:
component.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>
component.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);
}
}
在我的formarray中使用此代码会生成radiobuttons,其中一个选项被选中(只有2个选项)。我需要设计无线电按钮,使两个按钮保持不受控制。这样,当用户提交表单时,未选中的radiobuttons将创建验证错误,因为所有表单字段都是强制的。 如何确保默认情况下不检查任何单选按钮?
答案 0 :(得分:0)
没有像往常一样回应,所以我将继续回答我自己的问题。
要解决此问题,您需要在问题数组中为每个问题模型创建新的表单控件。为表单控件设置validation.required。
然后通过表单控件迭代选择模型,默认情况下取消选中radiobutton。