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

模板:

<form #loginForm="ngForm" (ngSubmit)="login(loginForm)" id="loginForm">
  <div class="login-content" fxLayout="column" fxLayoutAlign="start stretch">
    <md-input-container>
      <input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email">
    </md-input-container>
    <md-input-container>
      <input mdInput placeholder="Password" type="password" name="password" required [(ngModel)]="password">
    </md-input-container>
    <p class='error' *ngIf='loginFailed'>The email address or password is invalid.</p>
    <div class="extra-options" fxLayout="row" fxLayoutAlign="space-between center">
     <md-checkbox class="remember-me">Remember Me</md-checkbox>
      <a class="forgot-password" routerLink='/forgot-password'>Forgot Password?</a>
    </div>
    <button class="login-button" md-raised-button [disabled]="!loginForm.valid">SIGN IN</button>
     <p class="note">Don't have an account?<br/> <a [routerLink]="['/register']">Click here to create one</a></p>
   </div>
 </form>

登录方法:

 @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之外,我还尝试设置电子邮件。valid标志为false,并设置loginForm。无效也为真。这些都不会导致输入显示其无效状态。


当前回答

虽然已经晚了,但下面的解决方案对我有用。

    let control = this.registerForm.controls['controlName'];
    control.setErrors({backend: {someProp: "Invalid Data"}});
    let message = control.errors['backend'].someProp;

其他回答

在组件:

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

在HTML中:

<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email"  #email="ngModel">
<div *ngIf="!email.valid">{{email.errors| json}}</div>

补充茱莉亚·帕斯科娃的答案

在组件中设置验证错误:

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

清除组件中的验证错误:

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

使用null清除错误时要小心,因为这将覆盖所有错误。如果你想保留一些,你可能必须先检查是否存在其他错误:

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

你也可以将viewChild的“类型”更改为NgForm,如下所示:

@ViewChild('loginForm') loginForm: NgForm;

然后以@Julia提到的相同方式引用控件:

 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'].setErrors({ 'incorrect': true});
      this.loginForm.controls['password'].setErrors({ 'incorrect': true});
    });
  }

将Errors设置为null将清除UI上的错误:

this.loginForm.controls['email'].setErrors(null);

在material 2的新版本中,它的控件名称以mat前缀setErrors()开始不起作用,相反,Juila的答案可以更改为:

formData.form.controls['email'].markAsTouched();

Angular文档中的这个示例可能会有所帮助: <input type="text" id="name" name="name" class="form-control"

      required minlength="4" appForbiddenName="bob"
      [(ngModel)]="hero.name" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert">

  <div *ngIf="name.errors?.['required']">
    Name is required.
  </div>
  <div *ngIf="name.errors?.['minlength']">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors?.['forbiddenName']">
    Name cannot be Bob.
  </div>

</div>