How can I manually set an Angular form field as invalid?

后端 未结 9 1646
野的像风
野的像风 2020-11-28 01:58

I am working on a login form and if the user enters invalid credentials we want to mark both the email and password fields as invalid and display a message that says the log

9条回答
  •  情深已故
    2020-11-28 02:37

    You could also change the viewChild 'type' to NgForm as in:

    @ViewChild('loginForm') loginForm: NgForm;
    

    And then reference your controls in the same way @Julia mentioned:

     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});
        });
      }
    

    Setting the Errors to null will clear out the errors on the UI:

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

提交回复
热议问题