The error with removing the form field control in Angular 7 persists

I am currently in the process of designing a registration page that includes fields for confirming passwords and emails. Users are required to re-enter their password and email address. Below is the structure of the FormGroup:

ngOnInit() {
this.basicInfo = this.formBuilder.group({
  userName: ['', [Validators.required, Validators.minLength(5)]],
  firstName: ['', Validators.required],
  lastName: ['',Validators.required],

  emails: this.formBuilder.group({
    email: ['', [Validators.required, Validators.email]],
    emailConfirm: ['', [Validators.required, Validators.email]],
  }, {validators: SignUpComponent.checkEmailMatch}),

  passwords: this.formBuilder.group({
    password: ['', [Validators.required]],
    passwordConfirm: ['', Validators.required]
  }, {validators: SignUpComponent.checkPasswordMatch})
});

The validation function for the password fields is as follows (the same principle applies for the email fields):

static checkPasswordMatch(group: FormGroup) {
  let password = group.get('password');
  let passwordConfirm = group.get('passwordConfirm');
  if (password == null || passwordConfirm == null) return null; // prevent errors
  let match = password.value === passwordConfirm.value;
  if (!match) {
    passwordConfirm.setErrors({passwordMatchError: true});
    return {passwordMatchError: true};
  } else {
    return {passwordMatchError: null};
  }
}

Expected Outcome:

The validation should update whenever there are changes to either the password or passwordConfirmed, and display an error on the passwordConfirmed field if the values do not match.

Current Issue:

The error persists even after editing the passwordConfirmed field. The error displays properly when either field is modified.

Solution Attempted

I attempted to modify the conditional statement in the validator to eliminate the error from passwordConfirm:

if (!match) {
  passwordConfirm.setErrors({passwordMatchError: true});
  return {passwordMatchError: true};
} else {
  passwordConfirm.setErrors({passwordMatchError: null}); <-- this line
  return {passwordMatchError: null};
}

However, this action did not remove the error. Instead, it simply set the error value to null. The field remained marked as invalid, and the error persisted, which was confirmed by the console log shown here:

https://i.sstatic.net/C6wpV.png

Are there alternate methods to manually eliminate an error from a form control, or is there another approach to resolving this issue?

(Angular & Angular forms version 7.2.0)

Answer №1

Do not manually set an error using the setErrors method. When working with custom validators, simply return:

return { myErrorName: true };

if the input is not valid, and return:

return null;

if it is valid.

Update your validator function to look like this:

checkPasswordMatch(group: FormGroup) {
  let password = group.get('password');
  let passwordConfirm = group.get('passwordConfirm');
  if (!password && !passwordConfirm) return null;
  let match = password.value === passwordConfirm.value;
  return match ? null : { passwordMatchError: true};
}

Check out the DEMO here

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

TypeScript combines strong typing for arrays into a unified array of objects

I developed a JavaScript function that can merge multiple arrays into an array of objects based on provided key names. Here’s an example: const mergeArraysToSeries = (arrs, keys) => { const merged = []; for (let dataIndex = 0; dataIndex < arrs ...

An analysis of Universal Angular.io and Prerender.io from the viewpoint of Googlebot

Currently, my website is set up with Angular 1.4.x and prerender.io, which delivers static cached pages to Googlebot. Googlebot visits each page twice - once by hitting the URL directly, and then again by appending ?_escaped_fragment_ to the URL to access ...

Ways to emit a value from an observable once it is defined?

Is it feasible to create an observable that can wrap around the sessionStorage.getItem('currentuser')? This way, calling code can subscribe and retrieve the value only after it has been set in the sessionStorage. Do you think this is achievable? ...

Typescript enhances Solid JS by using the "as" prop and the "component" prop

Hey there, I've been experimenting with solid-js lately and I'm facing a challenge integrating it with typescript. My objective is to make my styling more modular by incorporating it within my components. type RelevantTags = Exclude<keyof ...

What is the process for implementing a unique Angular theme across all components?

I created a unique Angular theme called 'my-theme.scss' and added it to the angular.json file. While it works with most Angular Elements, I am facing issues getting it to apply to certain HTML Elements inside Angular Components. For example: < ...

Contrasting `Function` with `(...args: any[]) => any`

Can you explain the difference between Function and (...args: any[]) => any? I recently discovered that Function cannot be assigned to (...args: any[]) => any. Why is that so puzzling? declare let foo: Function; declare let bar: (...args: an ...

NestJs encountering issues with reading environment variables

I used the instructions from the Nest documentation to set up the configuration, however, it's not functioning correctly. app.module.ts @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TypeOrmModule.forRoot(config), AuthMo ...

Module not found when attempting lazy loading routing in Angular2 RC5

Having some challenges implementing RC5 changes in my app, particularly when it comes to lazy loading modules within the routing. Here's the file structure for the affected files in my app: /app /components/meda/meda.module.ts /components/meda ...

Typescript is asserting that the React class component has a property, despite what the component itself may suggest

I'm running into an issue with React refs and class components. Here's my simplified code snippet. I have a component called Engine with a property getInfo. In my test, I check for this.activeElement &&, which indicates that it's no ...

TypeScript is still throwing an error even after verifying with the hasOwnProperty

There exists a type similar to the following: export type PathType = | LivingstoneSouthernWhiteFacedOwl | ArakGroundhog | HubsCampaigns | HubsCampaignsItemID | HubsAlgos | HubsAlgosItemID | TartuGecko | HammerfestPonies | TrapaniSnowLeop ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

Developing dynamic-sized tuples in TypeScript

Recently, I was attempting to develop a zipper for arrays. For instance, if the user inputs 3 arrays with sizes of 3, 5, and 12, the output array of tuples would be the size of the largest array. The output consists of tuples containing elements at a speci ...

Tips for creating a unique custom rounded underline effect in an Angular Material Tab

Our design team has requested that we incorporate underlines that resemble the top half of a rectangle with rounded corners. We are currently using Angular Material, but I am facing difficulties in styling the existing tabs component (https://material.angu ...

Exploring Angular: A Guide to Importing Material Components

Trying to incorporate elements such as sliders and tooltips into my project, but encountering issues with imports. I've experimented with adding the import statement for MatSliderModule in various locations like app.module.ts and specific component mo ...

Error encountered during package installation: npm command terminated with exit code 1

When working with Angular 2, I consistently encounter the same issue across all of my projects. Strangely, these issues are normally resolved when building on a different PC. view image description here ...

The InAppBrowser seems to have trouble loading pages with cookies when I attempt to navigate back using the hardware back button

In my Ionic/Angular application, I utilize the InAppBrowser plugin to access a web application for my company. The InAppBrowser generally functions properly; however, there is an issue with a cookie within the web application that controls filters for cert ...

Angular: utilizing two instances of the <router-outlet> within a single component

Disclaimer: Despite finding a similar question on Stack Overflow with an accepted answer that did not solve my issue, I am still facing a problem. The challenge I am encountering is needing to use the same "router-outlet" twice in my main component. Howev ...

Error: Trying to access 'MaterialModule' before it has been initialized results in an uncaught ReferenceError

I have been working on a form for a personal project and attempted to implement a phone number input using this example: . However, after trying to integrate it into my project, I encountered an error. Even after removing the phone number input code, the e ...

Encounter an error message "Expected 0 type arguments, but received 1.ts(2558)" while utilizing useContext within a TypeScript setting

Encountering the error mentioned in the title on useContext<IDBDatabaseContext> due to the code snippet below: interface IDBDatabaseContext { db: IDBDatabase | null } const DBcontext = createContext<IDBDatabaseContext>({db: null}) Despite s ...

Is there a way to insert a button within a table that will allow me to easily insert new rows and columns?

<head> No content available at the moment. <!-- Here is my code --> <h1>Reserve Your Hall Form</h1> <form class="form-horizontal"> <table class="form-group table table-bordered table-hover"> ...