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

相关内容

热门资讯

透视教程书!红龙poker辅助... 透视教程书!红龙poker辅助工具(透视)pokemmo手机辅助软件(辅助)总是存在有插件(哔哩哔哩...
围绕透视问题!wepoker辅... 围绕透视问题!wepoker辅助器下载(透视)闲聚大联盟辅助(一贯存在有辅助软件)-哔哩哔哩1、游戏...
透视安装!安装不了wepoke... 透视安装!安装不了wepoker(透视)逗娱科技碰胡辅助(都是存在有辅助辅助器)-哔哩哔哩1、全新机...
透视诀窍!pokemmo辅助工... 透视诀窍!pokemmo辅助工具(透视)fishpoker透视(辅助)竟然一直总是有插件(哔哩哔哩)...
现场直击!hhpoker可以控... 现场直击!hhpoker可以控制牌吗(透视)多乐跑小程序如何开辅助(本来是真的辅助安装)-哔哩哔哩1...
透视方式!哈糖大菠萝攻略(透视... 透视方式!哈糖大菠萝攻略(透视)约局吧作必弊脚本(辅助)确实有攻略(哔哩哔哩)1、超多福利:超高返利...
网友热议!wepoker私人局... 您好,上饶辅助工具这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
透视积累!智星菠萝可以辅助吗(... 透视积累!智星菠萝可以辅助吗(透视)拱趴大菠萝自动计算机器人(辅助)竟然存在有神器(哔哩哔哩)1、下...
透视黑科技!wepoker透视... 透视黑科技!wepoker透视辅助下载(透视)道游拼十辅助器(都是真的有辅助修改器)-哔哩哔哩1、首...
透视大纲!pokerworld... 透视大纲!pokerworld软件(透视)德州辅助工具到底怎么样(辅助)切实一直都是有软件(哔哩哔哩...