角度反应形式的错误警报延迟一步出现 [英] Error alerts in angular reactive forms appear one step late

查看:0
本文介绍了角度反应形式的错误警报延迟一步出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是角度8,我正在尝试创建一个带有反应性表单的注册表。我已创建一些警报消息以显示验证错误。

但是,将显示上一个警报而不是当前警报!(晚了一步)

app.Component.ts文件:

    import { Component } from '@angular/core';
    import { FormBuilder, Validators, FormControl } from '@angular/forms';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {

      form = this.fBuilder.group({
        userName: ['', [
          Validators.required,
          Validators.minLength(3),
          this.userNameValidation.bind(this)
        ]]
      });

      requiredError: boolean;
      minLengthError: boolean;

      constructor(private fBuilder: FormBuilder) { }

      // User Name Validation
      userNameValidation(control: FormControl) {
        if (control.hasError('required') && control.dirty) {
          this.requiredError = true;
        } else {
          this.requiredError = false;
        }

        if (control.hasError('minlength') && control.dirty) {
          this.minLengthError = true;
        } else {
          this.minLengthError = false;
        }
      }
    }

app.Component.html文件:

    <form [formGroup]="form">
      <label>User Name: </label>
        <input formControlName="userName" type="text">
    </form>

    <!-- alerts -->
    <p *ngIf="requiredError">User Name is required</p>
    <p *ngIf="minLengthError">User Name must be at least 3 characters</p>

这是一个简单的StackBlitz,说明了我的意思:

Stackblitz Example 🚀🚀

尝试键入一个字母,然后将其删除,看看会发生什么情况。

提前谢谢!

推荐答案

根据对其他答案的评论,您希望"将错误发送到另一个组件"。如果您确实需要定制验证器,我们需要记住,角度表单实际上是异步的,因此需要额外的标记才能正确计算表单。我从来不建议在异步函数中使用setTimeout,但我们可以在等待一段时间后就知道表单值已经设置好了,所以可以安全地使用它。因此,将所有内容包装在超时内:

setTimeout(() => {
  if (control.hasError("required") && control.dirty) {
    this.requiredError = true;
  } else {
    this.requiredError = false;
  }

  if (control.hasError("minlength") && control.dirty) {
    this.minLengthError = true;
  } else {
    this.minLengthError = false;
  }
});

STACKBLITZ

但如果您的模板中有<hello></hello>这样的子组件,并且您希望通过@Input将错误发送给该子组件,则不需要使用上述方法,您也可以只将有效性的布尔值发送给子组件,如...

<hello *ngIf="form.get('userName').dirty" [requiredError]="form.hasError('required', 'userName')"></hello>

并在您的孩子身上感染它,例如:

@Input() requiredError: boolean;

ngOnChanges() {
  if (this.requiredError) {
    alert('field required!')
  }
}

STACKBLITZ

这篇关于角度反应形式的错误警报延迟一步出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆