Working on the login feature for my products-page using Angular 7 has presented some unexpected behavior. I want to show specific validation messages for different errors, such as displaying " must be a valid email " if the input is not a valid email address and showing " email is required " if the field is left blank. Once the user starts typing, the required message disappears and only the valid email error remains visible. Below is a snippet of my code.
Addproduct.component.html
I am attempting to render the error messages within span elements when an error occurs, but it's not functioning as expected.
<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
In the controller file, despite trying to simplify the validation rules, the intended behavior is still not achieved.
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;
}
}
The validation scripts were also adjusted, but the issue persists.
ngOnInit() {
this.loginForm = this.fb.group({
email : new FormControl('', [Validators.required,Validators.email]),
password : new FormControl('', [Validators.required,Validators.min(6)])
});
}
An error message is being generated as shown in this image link - https://i.sstatic.net/UbKnJ.jpg