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

Angular中如何为FormArray设置字段必填验证?

Angular FormArray 字段必填验证及单独提示解决方案

组件代码修正

核心是为每个FormArray内的FormControl添加Validators.required验证器,同时修正提交逻辑中的笔误:

import { Validators } from '@angular/forms'; // 导入验证器模块

targetStudentForm: FormGroup;
isSubmitted = false; // 声明提交状态变量

constructor(private formBuilder: FormBuilder) {
  this.targetStudentForm = this.formBuilder.group({
    requirements: this.formBuilder.array([])
  }); 
}

get requirements(): FormArray {
  return this.targetStudentForm.controls.requirements as FormArray;
}

addReqItem() {
  // 新增字段时绑定必填验证
  this.requirements.push(new FormControl("", Validators.required));
}

// 初始化回显数据(建议放在ngOnInit生命周期钩子中)
ngOnInit() {
  if (this.course?.learns?.length) {
    for (const item of this.course.learns) {
      // 回显已有数据时同样绑定验证,已有内容会自动通过验证
      this.requirements.push(new FormControl(item, Validators.required));
    }
  } else {
    this.requirements.push(new FormControl("", Validators.required));
  }
}

targetStudentSubmit() {
  this.isSubmitted = true;
  // 修正笔误:将this.form改为this.targetStudentForm
  if (this.targetStudentForm.invalid) return;
  console.log(this.targetStudentForm.value);
}

关键说明

  • 必须导入Validators模块才能使用必填验证规则;
  • 无论是新增空字段还是回显已有数据,创建FormControl时都要传入Validators.required,确保数组内每个字段都受验证约束;
  • 提交函数中修正了表单对象的引用错误,避免验证判断失效。

模板代码修正

调整提示显示逻辑,让单个字段单独触发警告,而非依赖整个表单的状态:

<div formArrayName="requirements" *ngFor="let requirement of requirements.controls; let i = index">
  <input
    type="text"
    class="form-control"
    [formControlName]="i"
  />
  <!-- 仅当前字段无效,且表单已提交/字段被触摸时显示提示 -->
  <small 
    *ngIf="requirement.invalid && (isSubmitted || requirement.touched)" 
    class="form-text text-danger"
  >
    This field is required
  </small>
</div>

关键说明

  • requirement.invalid精准判断当前数组项的控件是否未通过必填验证;
  • isSubmitted || requirement.touched控制提示时机:要么用户点击过提交按钮,要么用户触摸过该输入框,避免页面加载时就显示所有警告;
  • 输入内容后,控件会自动变为有效状态,对应提示会立刻消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:05:25