Angular单选按钮必填验证失效,提交无错误提示求助
Angular单选按钮必填验证不生效的解决方案
你的问题出在错误提示的显示条件依赖控件的touched状态——如果用户从未点击过单选按钮组,控件不会被标记为touched,哪怕提交时表单无效,错误提示也不会显示。同时onSubmit里的console.log(option)会报错,因为option未定义。
下面是两种解决方法:
方法一:提交时手动标记所有控件为已触摸
修改hotel.component.ts的onSubmit方法,先调用markAllAsTouched()把所有表单控件标记为已触摸,这样错误提示就会触发:
import { Component } from '@angular/core'; import { CommonModule, Location } from '@angular/common'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-hotel', // 补充缺失的Component装饰器,需根据实际项目调整 templateUrl: './hotel.component.html' }) export class HotelComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ option: ['', Validators.required], }); } onSubmit() { // 先标记所有控件为已触摸 this.form.markAllAsTouched(); if (this.form.valid) { // 修正变量未定义问题,获取单选按钮的值 console.log(this.form.get('option')?.value); } } }
方法二:添加提交状态变量控制错误提示
通过一个submitted变量记录表单是否被提交过,结合touched状态一起判断错误提示的显示:
修改hotel.component.ts
import { Component } from '@angular/core'; import { CommonModule, Location } from '@angular/common'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-hotel', templateUrl: './hotel.component.html' }) export class HotelComponent { form: FormGroup; submitted = false; // 添加提交状态变量 constructor(private fb: FormBuilder) { this.form = this.fb.group({ option: ['', Validators.required], }); } onSubmit() { this.submitted = true; if (this.form.valid) { console.log(this.form.get('option')?.value); } } }
修改hotel.component.html的错误提示条件
<div *ngIf="(form.controls['option'].touched || submitted) && form.controls['option'].invalid"> <div *ngIf="form.controls['option'].hasError('required')" class="error">请选择一个选项</div> </div>
另外注意:原代码中HotelComponent缺少@Component装饰器,这会导致组件无法正常工作,需要补充(根据你的项目实际情况调整selector和templateUrl)。
内容的提问来源于stack exchange,提问作者zack
相关产品推荐
相关产品推荐

