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

相关内容

热门资讯

透视曝光!hhpoker透视方... 透视曝光!hhpoker透视方法,hhpoker有没有作弊辅助-本来真的有辅助神器(哔哩哔哩)1、金...
透视详情!wpk是真的还是假的... 透视详情!wpk是真的还是假的,wpk真的有透视嘛-本来存在有辅助工具(哔哩哔哩)1、实时透视辅助更...
透视揭幕!购买的wpk辅助在哪... 透视揭幕!购买的wpk辅助在哪里下载,wpk软件是真的吗-真是一直总是有辅助插件(哔哩哔哩)是不是有...
透视分享!wepoker有没有... 透视分享!wepoker有没有挂,wepoker数据分析-一贯是真的有辅助脚本(哔哩哔哩)1、免费脚...
透视了解!wepoker私人局... 透视了解!wepoker私人局有透视吗,WePoKer辅助器-确实一直都是有辅助教程(哔哩哔哩)1、...
透视辅助!wpk真的有透视嘛,... 透视辅助!wpk真的有透视嘛,wpk真吗-本来是真的有辅助app(哔哩哔哩)1、透视辅助!wpk真的...
透视详情!wepoker私人局... 透视详情!wepoker私人局辅助器怎么用,wepokerh5破解-确实一直都是有辅助工具(哔哩哔哩...
透视详情!智星德州插件2024... 透视详情!智星德州插件2024最新版,pokemmo脚本-一直真的有辅助脚本(哔哩哔哩)1、上手简单...
透视分享!hhpkoer辅助挂... 透视分享!hhpkoer辅助挂是真的吗,hhpoker德州牛仔视频-果然有辅助神器(哔哩哔哩)1、完...
透视教你!德州局怎么透视,模拟... 透视教你!德州局怎么透视,模拟器打开hhpoker-切实一直总是有辅助技巧(哔哩哔哩)1、点击下载安...