angular - 如何确保在 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 个选项)。我需要设计单选按钮,使两个按钮都保持未选中状态。这样当用户提交表单时,未选中的单选按钮将产生验证错误,因为所有表单字段都是强制性的。如何确保默认情况下不检查任何单选按钮?
解决方案
像往常一样没有回应,所以我将继续回答我自己的问题。
要解决这个问题,您需要在问题数组中为每个问题模型创建新的表单控件。为表单控件设置validation.required。
然后通过表单控件迭代选择模型,默认情况下未选中单选按钮。
推荐阅读
- regex - 即使 regex101 返回匹配,正则表达式仍然返回 false
- java - Java 方程式中的引号
- python - 如何使用 OpenCV 将数组(帧)列表保存到视频中?
- mysql - Hive:java.sql.SQLSyntaxErrorException:表'metastore.dbs'不存在
- python-3.x - 如何保存 TF2 训练的模型并再次使用它进行推理?
- c - 'div_t' 类型的编译器错误操作数,其中 C 中需要算术或指针类型
- python - Python 请求发现代理延迟
- python - 从列表中打印特定值(python中的文本文件)
- c - 如何避免在函数中传递“冗余”参数?
- python - 检查值是否是另一对pyspark的键