如何手动将Angular表单字段设置为无效?

29 浏览
0 Comments

如何手动将Angular表单字段设置为无效?

我正在开发一个登录表单,如果用户输入了无效的凭据,我们希望将电子邮件和密码字段标记为无效,并显示一条消息,说明登录失败。我该如何在观察回调中设置这些字段为无效?

模板:

The email address or password is invalid.

Remember Me Forgot Password?

Don't have an account? Click here to create one

登录方法:

 @ViewChild('loginForm') loginForm: HTMLFormElement;
 private login(formData: any): void {
    this.authService.login(formData).subscribe(res => {
      alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
    }, error => {
      this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
      this.loginForm.controls.email.invalid = true;
      this.loginForm.controls.password.invalid = true; 
    });
  }

除了将输入设为无效标志设置为true之外,我还尝试将email.valid标志设置为false,并将loginForm.invalid设置为true。但是这些都不会导致输入显示其无效状态。

0
0 Comments

在 Julia Passynkova 的回答中补充

设置组件的验证错误:

formData.form.controls['email'].setErrors({'incorrect': true});

取消组件的验证错误:

formData.form.controls['email'].setErrors(null);

小心使用 null 去取消错误,因为这样会覆盖所有的错误。如果你想要保留一些错误,你可能需要先检查是否存在其他的错误:

if (isIncorrectOnlyError){
   formData.form.controls['email'].setErrors(null);
}

0
0 Comments

在组件中:\n

formData.form.controls['email'].setErrors({'incorrect': true});

\n并且在HTML中:\n


{{email.errors| json}}

0