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

Angular中动态设置必填校验后如何仅在输入框被触碰时显示报错

问题解决方法

原因说明

动态给表单控件添加Validators.required校验后,空值控件会立即变为invalid状态,同时你的错误提示判断逻辑未限制用户交互状态,导致报错直接展示。

具体修复步骤

1. 修正TS动态设置校验逻辑

给控件设置完校验规则后,需要重置控件的交互状态为「未触碰、未修改」,同时更新校验状态:

// 修正getStarted方法逻辑,把setRequired放到if判断内
getStarted(isExisting: boolean) { 
  if(isExisting === false) {
    this.setRequired()
  }
}

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

initFormGroup() {
  this.modelForm = this.formBuilder.group({
    id: [this.model.id || 0],
    emailAddress: [this.model.emailAddress, Validators.required],
    firstName: [this.model.firstName],
    roleId: [this.model.roleId],
    lastName: [this.model.lastName],
    // 原代码用到了companyName字段,此处补充声明
    companyName: [this.model.companyName]
  });
}

// 修正setRequired为标准方法格式
setRequired() {
  const fields = ['firstName', 'lastName', 'companyName'];
  fields.forEach(field => {
    const control = this.modelForm.get(field);
    control.setValidators(Validators.required);
    // 重置控件交互状态为未触碰、未修改
    control.markAsUntouched();
    control.markAsPristine();
    // 更新校验状态,避免触发不必要的父控件事件
    control.updateValueAndValidity({onlySelf: true, emitEvent: false});
  })
}

2. 修改HTML错误提示判断

在报错条件中增加控件touched(已触碰)的判断,确保只有用户触碰过输入框后才展示错误:

<mat-form-field class="full-width" appearance="fill" style="margin-top: 20px;">
  <mat-label>Last name</mat-label>
  <input matInput formControlName="lastName">
  <mat-error *ngIf="modelForm.get('lastName').hasError('required') && isExisting === false && modelForm.get('lastName').touched">
    Last name is required.
  </mat-error>
</mat-form-field>

如果你需要用户修改过输入值才展示错误,把判断条件里的touched换成dirty即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 08:18:04