Angular keeps FormArray elements' validity up-to-date as new elements are added to the array

I am facing an issue where I do not want the validators to run unnecessarily. Every element of FormArray is being validated asynchronously, so I prefer the validators to be triggered only when the control's value actually changes. It seems odd that validators are not executed when the value of FormArray changes, but rather only when a new element is added.

To see this behavior in action, you can visit: https://stackblitz.com/edit/angular-reactive-forms-tkdu1n?file=app%2Fapp.component.ts

I would greatly appreciate any assistance with this issue.

Answer №1

It seems like the FormArray triggers the validator for each nested FormControl whenever a new FormControl is added, and unfortunately there doesn't seem to be a way around it...

After exploring your stackblitz example, I decided to devise a stateful validator with a closure, and surprisingly, it worked like a charm:

form: FormArray;

ngOnInit() {
  this.form = new FormArray([]);
  this.form.push(new FormControl("test", null, this.createValidator()));
}

addControl() {
  this.form.push(new FormControl(null, null, this.createValidator()));
}

createValidator() {
  let previousValue;
  return (c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
    if (c.value == previousValue) {
      return Observable.of(null);
    } else {
      previousValue = c.value;
      return Observable.of(null).delay(1000);
    }
  };
}

Modified Stackblitz

I hope this information proves useful!

Answer №2

A simple update can solve this issue:

replace Observable.of(null).delay(1000) with Observable.of(null).delay(0);

By changing the delay to 0ms, you ensure that only the current instance is checked without affecting the statuses of other instances. Keeping it at 1000ms may disable and block reachability for other values.

I hope this solution works for you!

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 could be causing my Mongoose controller to not be executed?

I am currently working on developing an API using Mongoose and Express. I have successfully set up several routes that are functioning properly. However, I am facing an issue with a specific route that is intended to search for a model called Subassembly b ...

What is the best tool for setting up an ftp connection to a z/OS mainframe and downloading files to the local machine within an angular web application?

My goal is to allow the user of the webapp to enter a specific file located on the server via a text field, and then have that file downloaded to their local machine. There's also an optional feature where the user can input the login credentials for ...

"Encountering issues with ngrx store selector when importing app from a custom

My Angular library includes a store implementation and is distributed as an NPM package, used in various Angular applications. I encountered an error when attempting to use a ngrx store selector exported from the library in a different Angular project: ...

International replacement of external interface exportation

Currently, I am utilizing the @react-native-firebase/messaging library and invoking the method messaging().onNotificationOpenedApp(remoteMessage => ....) I am aiming to replace the property data within the type of remoteMessage in order to benefit from ...

What is the most efficient method for incorporating React into Wordpress while using Typescript?

Is it possible for me to utilize the React / React-Dom scripts that Wordpress has enqueued in my bundled javascript, while still being able to use the -dev installed React for development purposes? The javascript files are designed for a WordPress plugin ...

Implementing Observable lambdas in Angular templates for easy function calling

Within a component, I have the following code snippet: public hasFoo$: Observable<(name: string) => boolean> = ... Now, I would like to use this multiple times in my template with a stepper: <mat-vertical-stepper> <mat-step *ngIf="ha ...

Type inference and the extends clause in TypeScript 4.6 for conditional types

My focus was on TypeScript 4.7 when I created the following types: const routes = { foo: '/foo/:paramFoo', bar: '/bar/:paramFoo/:paramBar', baz: '/baz/baz2/:paramFoo/:paramBar', } as const; type Routes = typeof routes; ...

Is Angular2 detecting changes based on value equivalence or reference equality?

I am currently working with Angular2-RC.1 and I've noticed a significant decrease in performance when setting up a component with a large dataset. The component I'm using is a tabular one (which involves Handsontable) and it has an Input property ...

Unsupported method 'keys' for the specified object - (Internet Explorer 11)

I'm having trouble identifying the issue in Internet Explorer 11. The application functions perfectly without any problems in other browsers such as Chrome and Firefox. https://i.stack.imgur.com/5QvML.png ...

The object may be null even after being enclosed in an if statement

In my Vue component, I have implemented the following method: dataURLtoBlob(dataurl: string): Blob { const arr: string[] = dataurl.split(","); if (arr) { if (arr[0]) { const mime = arr[0].match(/:(.*?);/)[1]; ...

Dynamic styling with Angular's @Component decorator allows for the seamless application of styles

Angular 13 In my @Component, I am trying to set up dynamic values for the styles, but it is not working. styles: [ ` .k-daterangepicker .k-dateinput { width: {{myWidth}}; } `, ], What is the correct way to change the . ...

Connecting to a port in node.js is not possible

Currently, I am using port 4200 for my Angular application and port 3000 for my Node.js server. However, I am facing an issue where when I run the Angular application, the Node.js server does not work and I encounter a "Connection refused" problem. Can a ...

Methods to troubleshoot problem of angular component loading issue in firefox with ViewEncapsulation.Native

I am encountering a problem with loading an angular component using ViewEncapsulation.Native in firefox, edge, and ipad chrome. Interestingly, there is no issue on safari on mac, chrome on windows, or chrome on android. Error: hostEl.createShadowRoot is ...

How to filter ngFor elements in Angular 2 based on user input?

Is there a method for filtering elements rendered through *ngFor based on real-time user input following each keyup event? ...

Encountering a problem in Angular 2 when initiating a project

I recently started learning Angular 2. I set up my project and attempted to launch it using npm. Initially, everything was working smoothly, but after a few days, when I tried to start it again, an error appeared in the command prompt. SyntaxError: Unexpe ...

OCI: Predict expenses based on a selection of virtual machines

Seeking to determine the anticipated cost of a selection of instances within OCI utilizing the TypeScript SDK. Oracle offers a tool called Cloud Cost Estimator for configuring and dynamically displaying cost estimates. Is it possible to achieve this throug ...

Error encountered when attempting to close a MatDiaLog in Angular as the close button is unable to read the property 'close' of null

Looking to develop a component that incorporates multiple content projects in angular 6. Here's the code I used in app.component.html: <popup> <button buttonTrigger mat-button><span >Open the popup!</span></button> ...

Developing a custom React hook that utilizes the useContext functions

When attempting to utilize a function within a custom hook, I encounter the following error message: Error: tglCartao is not defined The custom hook code in UseCartao.tsx is as follows: export interface ICartaoContext { idToggleKey : string; ...

The usage of Angular Tap is no longer recommended or supported

My Angular application contains the following HTTP interceptor: import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse } from '@angular/common/http'; ...

Challenge your TypeScript skills: convert snake_case to camelCase and back again

I am looking to develop a Typescript function that can deeply traverse a plain object and convert all snake_case keys to camelCase. Additionally, I need a function that can convert camelCase keys to snake_case throughout the object. While implementing thi ...