You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10中如何为多道单选按钮题目设置必填校验并显示错误提示

问题原因

  1. HTML表格结构不规范,<tr> 标签内直接放置文本和控件,没有嵌套 <td> 标签,会导致DOM解析异常,影响表单控件的状态同步
  2. 现有校验逻辑仅在控件被触摸(touched)或修改(dirty)时才展示错误提示,用户未操作过单选框时,控件状态不会触发校验,看起来就像校验失效
  3. 提交按钮仅在表单合法时启用,用户未作答任何题目时按钮一直处于禁用状态,也不会触发错误提示

修复方案

1. 修改HTML代码

修正表格结构,新增表单提交事件绑定,移除冗余的原生required属性(响应式表单已配置校验规则,原生属性可省略避免冲突)

<form [formGroup]="surveyForm" (ngSubmit)="onSubmit()">          
    <table class="table">
      <tbody>
        <tr><td>Question1</td></tr>                
        <tr>
          <td>
            <input type="radio" value="1" formControlName="ans1" id="ans1.opt1"> a
            <input type="radio" value="2" formControlName="ans1" id="ans1.opt2"> b    
          </td>
        </tr>
        <tr>
          <td>
              <div *ngIf="isValidInput('ans1')" class="alert alert-danger">
                 <div *ngIf="surveyForm.controls['ans1'].errors?.required">   
                    请选择答案
                  </div>
               </div>
          </td>
        </tr>
        <tr><td>Question2</td></tr>                
        <tr>
          <td>
            <input type="radio" value="1" formControlName="ans2" id="ans2.opt1"> a
            <input type="radio" value="2" formControlName="ans2" id="ans2.opt2"> b            
          </td>
        </tr>
        <tr>
          <td>
              <div *ngIf="isValidInput('ans2')" class="alert alert-danger">
                  <div *ngIf="surveyForm.controls['ans2'].errors?.required">   
                    <p>请选择答案</p>
                  </div>
              </div>
          </td>
        </tr>
        </tbody>
     </table>
     <button type="submit" class="btn btn-primary">提交</button>   
</form>

2. 修改TS代码

新增提交方法,提交时自动标记所有表单控件为touched状态,触发未作答题目的错误提示,同时调整控件初始值为null更符合未选择的状态

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-survey',
  templateUrl: './survey.component.html',
  styleUrls: ['./survey.component.css']
})
export class SurveyComponent {
  surveyForm!: FormGroup; 
  surveyInfo!: {
    ans1: number;
    ans2: number;          
  };
 
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.surveyForm = this.fb.group({
      ans1: [null, Validators.required],
      ans2: [null, Validators.required],                  
    });
  }

  isValidInput(fieldName: string): boolean {
    return this.surveyForm.controls[fieldName].invalid &&
      (this.surveyForm.controls[fieldName].dirty || this.surveyForm.controls[fieldName].touched);
  }

  onSubmit(): void {
    // 表单不合法时标记所有控件为已触摸,触发所有错误提示
    if (this.surveyForm.invalid) {
      Object.values(this.surveyForm.controls).forEach(control => {
        control.markAsTouched();
      });
      return;
    }
    // 表单合法时执行提交逻辑
    this.surveyInfo = this.surveyForm.value;
    console.log('提交数据:', this.surveyInfo);
  }
}

修复后效果

  • 每道题选择后对应的必填校验自动通过
  • 点击提交按钮如果有未作答的题目,会自动展示对应题目的必填错误提示
  • 两道题都完成选择后才会执行后续提交逻辑

内容的提问来源于stack exchange,提问作者user9805040

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:24:06