简体   繁体   中英

Angular form validation not displaying error message

I'm running a log in form to display an error if either of password or email is invalid So far this is what I have

<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>

and in my 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)
      })
  }

However the error message does not seem to be displayed when I've submitted an invalid user. Previously I have tested with

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

but the problem is it is only displayed according to where the field is being filled and not validate the field itself.

This is pretty much a long shot, but, you are assigning the error to the component, and usually that can fail only when you have changeDetection: ChangeDetectionStategy.OnPush declared in your component definition. If so, you only need to inject the change detector reference constructor(private cd: ChangeDetectorRef) {} and use it after you assign the error value in the .catch block, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM