【发布时间】:2021-11-15 04:09:03
【问题描述】:
我有 2 个带有单选按钮的两选项问题作为答案。如何使单选按钮成为必需,以便在未回答时显示消息?
This article解释了如何要求单选按钮,但是只有一个问题,如果我添加第二个问题它不起作用!
这是我的 .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);
}
【问题讨论】:
标签: angular validation radio-button radio-group