Search code examples
javascriptangulartypescriptangular-reactive-formsangular-validation

Strange errors with Angular Reactive Forms Validation


I'm testing a simple login functionality on my products-page component form using Angular 7 and I'm having this strange behaviour. I am trying to display the appropriate validation messages if an error exists, like if it is not a valid email, the " must be a valid email " message should display, and if the field is left blank, the " email is required ", error should display, and when you start typing, the required message disappears and only the valid email error message shows. This is my code.

Addproduct.component.html

So now I'm trying to render the span-messages if the error exists but it's not working.

<form [formGroup]="loginForm" class="login-container" (ngSubmit)="login()">            
    <p>
        <input class="form-control" type="email" placeholder="Email here" formControlName="email">
        <span *ngIf="f.email.errors.required">email is required</span>
        <span *ngIf="f.email.errors.email">must be a valid email</span>
    </p>            
    <p>
        <input class="form-control" type="password" placeholder="Password here" formControlName="password">
        <span *ngIf="f.password.errors.required">Password is required</span>
    </p>
    <p><button type="submit" class="btn btn-md btn-primary">Submit</button></p>        
</form>

Addproduct.component.ts

and this is the controller, I tried using the short notation for the validation rules but yet to no avail.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-addproduct',
  templateUrl: './addproduct.component.html',
  styleUrls: ['./addproduct.component.css']
})
export class AddproductComponent implements OnInit {

  loginForm:FormGroup;
  isSubmitted:boolean = false;

  constructor(
    private router:Router,
    private fb:FormBuilder
  ){}

  ngOnInit() { 
    this.loginForm = this.fb.group({           
      email : ['',  [Validators.required,Validators.email]],    
      password : ['', [Validators.required,Validators.min(6)]]
    });
  }

  get f(){
    return this.loginForm.controls;
  }

}

I also changed the validation scripts to this but still to no avail

ngOnInit() { 
   this.loginForm = this.fb.group({           
      email : new FormControl('',  [Validators.required,Validators.email]),    
      password : new FormControl('', [Validators.required,Validators.min(6)])
   });
}

and I am getting this error

enter image description here


Solution

  • You are checking for the presence of an error where no error might exist.

    You want something like this:

    f.email.errors?.required
    

    Or even:

    f.email?.errors?.required
    

    Do the same for the password field and anywhere else where the property might not exist when it is first called.