Angular响应式表单验证在设置子元素错误后无法触发
创始人
2024-10-30 08:00:19
0

问题背景:

在Angular中,当我们使用响应式表单时,我们可以通过setErrors方法来设置表单或表单控件的错误信息。但是,我们在设置子控件的错误信息后,可能会发现表单验证未触发。

解决步骤:

在父组件中,我们需要调用updateValueAndValidity()方法来通知表单进行重新验证。该方法会遍历表单的所有控件并更新其状态,然后再次验证表单的有效性。

以下是一个示例,当我们从服务端异步获取错误信息后,我们会对表单控件进行setErrors设置,然后在父组件中调用updateValueAndValidity()方法来重新触发表单验证:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserService } from './user.service';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
})
export class UserProfileComponent implements OnInit {
  userForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private userService: UserService,
  ) {}

  ngOnInit() {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required],
    });
  }

  onSubmit() {
    this.userService.updateProfile(this.userForm.value).subscribe(
      () => {
        // update profile success
      },
      err => {
        if (err.status === 400) {
          const errors = err.error.errors;
          for (const key in errors) {
            if (this.userForm.get(key)) {
              this.userForm.get(key).setErrors({ serverError: errors[key] });
            }
          }
          this.userForm.updateValueAndValidity();
        }
      },
    );
  }
}

在上述示例中,当服务端返回错误信息时,我们会将错误信息设置为serverError,然后通过setErrors

相关内容

热门资讯

分享认知!pokemomo辅助... 分享认知!pokemomo辅助工具(辅助挂)原来是真的有挂(有挂工具辅助软件)1、很好的工具软件,可...
终于知道!hhpoker脚本(... 终于知道!hhpoker脚本(辅助挂)好像有挂(有挂秘诀辅助脚本)1、打开软件启动之后找到中间准星的...
玩家攻略!哈糖大菠萝挂(辅助挂... 玩家攻略!哈糖大菠萝挂(辅助挂)都是是真的有挂(有挂教程辅助工具)1、用户打开应用后不用登录就可以直...
揭秘攻略!wepoker黑侠辅... 揭秘攻略!wepoker黑侠辅助器(辅助挂)竟然有挂(有挂透视辅助插件)1、许多玩家不知道辅助怎么退...
最新技巧!wepoker透视器... 最新技巧!wepoker透视器免费(辅助挂)原来真的是有挂(有挂头条辅助插件)运辅助工具,进入游戏界...
重大通报!hhpoker怎么破... 重大通报!hhpoker怎么破解(辅助挂)总是有挂(今日头条辅助器)重大通报!hhpoker怎么破解...
玩家必看科普!云扑克有透视吗(... 玩家必看科普!云扑克有透视吗(辅助挂)好像真的是有挂(果真有挂辅助方法)1、用户打开应用后不用登录就...
我来教大家!htx矩阵wepo... 我来教大家!htx矩阵wepoker辅助(辅助挂)其实存在有挂(证实有挂辅助技巧)1. 选牌创建新账...
程序员教你!pokerworl... 程序员教你!pokerworld辅助器(辅助挂)真是存在有挂(有挂攻略辅助教程)1、打开软件启动之后...
攻略讲解!hhpoker脚本(... 攻略讲解!hhpoker脚本(辅助挂)好像真的是有挂(有挂存在辅助方法)1、下载好脚本下载之后点击打...