我有 2 个带有单选按钮的二选题作为答案。我怎样才能使单选按钮成为必需的,以便在没有回答时显示一条消息?
这篇文章解释了如何要求单选按钮,但是只有一个问题,如果我添加第二个问题就不行了!
这是我的 .html 文件:
<form [formGroup]="surveyForm" >
<table class="table" >
<tbody >
<tr> Question1 </tr>
<tr> <input type="radio" value="1" formControlName="ans1" id="ans1.opt1" required > a
<input type="radio" value="2" formControlName="ans1" id="ans1.opt2" required > b
</tr>
<tr>
<div class="form-control alert alert-danger" id="ans1Error" style="display: none;"></div>
<div *ngIf="isValidInput('ans1')" class="alert alert-danger">
<div *ngIf="surveyForm.controls['ans1'].errors?.required">
Answer is required.
</div>
</div>
</tr>
<tr> Question2 </tr>
<tr> <input type="radio" value="1" formControlName="ans2" id="ans2.opt1" required > a
<input type="radio" value="2" formControlName="ans2" id="ans2.opt2" required > b
</tr>
<tr>
<div class="form-control alert alert-danger" id="ans2Error" style="display: none;"></div>
<div *ngIf="isValidInput('ans2')" class="alert alert-danger">
<div *ngIf="surveyForm.controls['ans2'].errors?.required">
<p> Answer is required.</p>
</div>
</div>
</tr>
</tbody>
</table>
<button [disabled]="!surveyForm.valid" type="submit" class="btn btn-primary" > Submit </button>
</form>
和.ts文件:
surveyForm!: FormGroup;
surveyInfo!: {
ans1: number;
ans2: number;
};
constructor( private fb: FormBuilder) { }
ngOnInit(): void {
this.initForm();
}
initForm(): void {
this.surveyForm = this.fb.group({
ans1: ['', Validators.required],
ans2: ['', Validators.required],
});
}
isValidInput(fieldName: any): boolean {
return this.surveyForm.controls[fieldName].invalid &&
(this.surveyForm.controls[fieldName].dirty || this.surveyForm.controls[fieldName].touched);
}
它的工作原理是表格按照你的要求去做。
如果您说您不知道为什么没有看到错误消息,那是因为没有取消选择无线电输入的本机方法。因此,当你点击radio input时,它有一个值,满足
Validators.required
的要求。
此外,如果表单无效,您还禁用了提交按钮。如果它没有被禁用,您可以在提交时运行另一个有效性检查并在那里显示错误。
Stackblitz 显示您的表单状态。
编辑: 您链接到的示例是这样做的:
<div *ngIf="isSubmitted && myForm.invalid">
<p>Please select either Gender</p>
</div>
提交功能是这样的:
templateForm(form: NgForm) {
this.isSubmitted = true;
if (!form.valid) {
return false;
} else {
alert(JSON.stringify(form.value))
}
}