Issues with Angular Reactive Forms Validation behaving strangely

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

Answer №1

You are looking to detect a potential error even if one does not currently exist.

Consider using the following syntax:

f.email.errors?.required

You could also try:

f.email?.errors?.required

Apply this approach to the password field and any other instances where the property may not be present initially.

Answer №2

Another option is utilizing

<div *ngIf="userInfoForm.hasError('required', ['email'])">Email is required</div>

In my view, this method proves to be simplifying the process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting a specific version of Node for a project on my local machine?

I am currently facing an issue with setting up Node across multiple developers' machines for a project. The challenge lies in the fact that not all team members are experienced in Node or JavaScript, and we need to ensure that everyone has the correct ...

What are different ways to modify a bytearray within a file using angular js, whether it is an .xlsx or other

I received a bytearray response from my API that was converted from a .xlsx file. I now need to open or download this bytearray in the browser after converting it back to its original file extension. Can anyone provide guidance on how to achieve this? I ...

Encountered an issue with resolving the module specifier while attempting to import a module

Whenever I attempt to import a module, I consistently encounter this error message Failed to resolve module specifier "mongodb". Relative references must start with either "/", "./", or "../". and I have searched ext ...

Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books. public getBooks(): Observable<Book[]>{ ...

Dynamic sliding box jumps instead of simply fading in/out

My app features both a navigation bar and a sub-navigation bar. Within the sub-navigation bar, users can click on a button that triggers the appearance of another sub-bar while hiding the original one. The new sub-bar should smoothly slide out from behind ...

Create a unique Bitcoin address using a derivation scheme

Starting with a derivation scheme that begins with tpub... for the testnet, I am looking to generate bitcoin addresses from this scheme. I also need a method that will work for the mainnet. Is there a library available that can assist me with this task? ...

Compel a customer to invoke a particular function

Is there a way to ensure that the build method is always called by the client at the end of the command chain? const foo = new Foo(); foo.bar().a() // I need to guarantee that the `build` method is invoked. Check out the following code snippet: interface ...

Angular: steps for connecting a component with a data service

I've been researching Angular extensively, reading countless documentation and blogs, but I still find myself more confused. One specific issue I encountered is with a button in my header that allows users to select their preferred language: <mat ...

Vuetify autocomplete with server-side functionality

I am looking to implement infinite pagination on the Vuetify autocomplete feature. My goal is to trigger the loading of a new page of items from the backend when I scroll to the end of the menu. Initially, I attempted using the v-intersect directive as fo ...

Sending a message to an iframe from a different origin using JavaScript

Just starting out with JavaScript and I'm attempting to send a message to my iframe in order to scroll it. Here is the code I am using: scroll(i) { var src = $("#iframe").attr("src"); $("#iframe").contentWindow.postMe ...

Enrich your HTML using AngularJS

CSS <div class="container"> <section> <p>{{content}}</p> </section> </div> script.js (function () { var script = function ($scope){ $scope.content = "example"; } }()); I am currently ...

Error encountered: Parsing error in Typescript eslint - The use of the keyword 'import' is restricted

My CDK application is written in typescript. Running npm run eslint locally shows no errors. However, when the same command is executed in a GitLab pipeline, I encounter the following error: 1:1 error Parsing error: The keyword 'import' is r ...

Troubleshooting: Vue.js custom select element not responding to blur event

Unique Scenario A custom autocomplete select component has been created that not only autocompletes but also allows for adding a new value if the result is not found. This functionality was discovered to be missing in the vue-select module. Explore the C ...

"An issue with AngularJS ngTable causing a delay in the rendering of Ajax

Struggling with ngTable Setup Having trouble mastering the use of ngTable by going through the ngTable ajax demo. I attempted to follow along with the example as closely as possible, but I'm encountering a deviation in defining an ngResource inline w ...

Incorporating map, forkJoin, and mergeMap into your code base can

I have a requirement to perform multiple API calls. The first API call returns a list of objects with the properties userId and propertyId. For each item in this list, I need to fetch additional information called userInfo and propertyInfo based on the I ...

Create allowances for specific areas

One of my methods involves the saving of an author using the .findOneAndUpdate function. The structure of AuthorInterface is as follows: export interface AuthorInterface { name: string, bio: string, githubLink: string, ...

Using Spry Validate for form validation in conjunction with Ajax submission

I'm currently facing an issue where I want my form to validate before the ajax call is made, but I can't seem to figure out the correct coding for this process. When I separate them, I am able to either post using ajax without validation or with ...

To utilize the span and input text increment functionality, simply use the required input type number and hold either the up or down arrow

Is it possible to increment the value of an input type number by 1 when holding down on a mobile device? <input type="text" id="number" value="1"> <span id="upSpan"> Up </span> $('#upSpan').on('touchstart', function ...

Ordering numbers in Angular2 using a custom pipe

In my Angular2 project, I am attempting to organize an array of strings based on numerical values using a custom pipe that was not authored by me. The code for the pipe is provided below: import { Pipe, PipeTransform } from "@angular/core"; @Pipe( { name ...

Error message: The variable "data" is not defined in next.js

Being new to React, I recently used getStaticprops to retrieve data from an API for a filter gallery project. However, I encountered an issue when trying to access the {props: data} outside of the blog function - it resulted in a Reference Error stating th ...