【问题标题】:Angular form validation not displaying error message角度表单验证不显示错误消息
【发布时间】:2019-10-16 09:26:15
【问题描述】:

如果密码或电子邮件无效,我正在运行登录表单以显示错误 到目前为止,这就是我所拥有的

<form [formGroup]="loginForm" (ngSubmit)="SignIn(email.value, password.value)">
  <mat-form-field>
    <input formControlName="email" name="email" matInput type="text" placeholder="email">
  </mat-form-field>
  <mat-form-field>
    <input formControlName="password" name="password" matInput type="password" placeholder="Password">
  </mat-form-field>
  <div *ngIf="errorCode" class="notification is-danger">
    Email and password does not match
  </div>
  <div class="d-flex flex-column align-items-center">
    <button mat-raised-button  class="button is-success w-100" type="submit" [disabled]="!loginForm.valid">
      Continue
    </button>
  </div>
</form>

在我的 ts 中

 ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', [
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ]],
      password: ['',
        Validators.required
      ],
    });
  }
SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
          this.ngZone.run(() => {
          this.router.navigate(['dashboard']);
        });
      }).catch((error) => {
        this.errorCode= error.message;
        console.log(this.errorCode)
      })
  }

但是,当我提交无效用户时,似乎没有显示错误消息。 以前我用

测试过
<div *ngIf="!loginForm.valid" class="notification is-danger">
   Email and password does not match
  </div>

但问题是它只根据字段填写的位置显示,而不是验证字段本身。

【问题讨论】:

  • 你能创建一个堆栈闪电战吗? ++为什么你的表单是在SignIn(...) 方法中定义的?

标签: angular validation angularfire angular-forms


【解决方案1】:

这是一个很长的尝试,但是,您将错误分配给组件,并且通常只有当您在组件定义中声明 changeDetection: ChangeDetectionStategy.OnPush 时才会失败。如果是这样,您只需要注入更改检测器引用constructor(private cd: ChangeDetectorRef) {} 并在.catch 块中分配错误值后使用它,如下所示:

}).catch((error) => {
 this.errorCode= error.message;
 console.log(this.errorCode)
 this.cd.detectChanges();
})

【讨论】:

  • 您能进一步详细解释一下吗?我已经尝试过一些教程,但它似乎破坏了我的表单组,在我的控制台中返回“无法读取未定义的属性'get'”
猜你喜欢
  • 2019-02-24
  • 2017-12-26
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2019-08-14
  • 2019-06-11
  • 1970-01-01
  • 2016-03-05
相关资源
最近更新 更多