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

相关内容

热门资讯

据相关数据显示!德普之星透视辅... 据相关数据显示!德普之星透视辅助软件激活码(透视)新九哥脚本下载(好像真的有辅助辅助器)-哔哩哔哩1...
日前!红龙poker作必弊指令... 日前!红龙poker作必弊指令(透视)海豹大厅超级三加一辅助(其实是有辅助软件)-哔哩哔哩1、玩家可...
网友热议!约局吧德州有挂吗(透... 网友热议!约局吧德州有挂吗(透视)红人阁自动挂机脚本(确实是真的辅助软件)-哔哩哔哩1、操作简单,无...
透视辅助!破解辅助插件wepo... 透视辅助!破解辅助插件wepoker(透视)开心十三张脚本(原来有辅助app)-哔哩哔哩开心十三张脚...
于此同时!wepoker俱乐部... 于此同时!wepoker俱乐部辅助器(透视)圣盛荆州晃晃三五七辅助(总是有辅助软件)-哔哩哔哩1、下...
透视神器!pokermaste... 透视神器!pokermaster破解版(透视)多乐小程序游戏辅助器(确实真的是有辅助软件)-哔哩哔哩...
据统计!aapoker怎么拿好... 据统计!aapoker怎么拿好牌(透视)九江讨赏辅助(本来是真的辅助工具)-哔哩哔哩该软件可以轻松地...
日前!wepoker辅助器有哪... 日前!wepoker辅助器有哪些功能(透视)微信小程序怎么开挂(一贯是真的辅助软件)-哔哩哔哩1、微...
随着!aapoker怎么设置抽... 随着!aapoker怎么设置抽水(透视)蜜瓜大厅辅助免费下载(本来有辅助辅助器)-哔哩哔哩1、玩家可...
据悉!wepoker破解器有用... 据悉!wepoker破解器有用吗(透视)来物局怎么开挂(竟然有辅助辅助器)-哔哩哔哩1、游戏颠覆性的...