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

Terminating a function during execution in JavaScript/TypeScript

Currently, I am in the process of developing a VSCODE extension using TypeScript. Within this extension, there is a particularly large function that is frequently called, but only the final call holds significance. As a solution, I am attempting to elimina ...

The template literal expression is invalid due to the "string | null" type when sending authorization

While working on implementing authorization, I encountered an error from Ts-eslint stating that there was an "Invalid type 'string | null' of template literal expression" when trying to execute the functionality. The data being retrieved from lo ...

The function is triggered by the button depending on its origin

Within my Header component, I have both a "create" and "search" button. This header is included on the customer, products, and sales pages. My question is how can I implement functions for creating and searching specific to each page. Do I need to create ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

Demonstrate JSON data using ngFor loop in Angular

Need some assistance here. Trying to display data from a .json file using a ngFor loop. However, I keep running into the following error in my code: Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgF ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Showing the AngularFireList data on the HTML page following successful retrieval

Does anyone know how to display an AngularFireList on an HTML page? import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import {AngularFireAuth} from 'angularfire2/auth'; import {AngularF ...

Angular2 ERROR: Unhandled Promise Rejection: Cannot find a matching route:

I'm facing an issue with my Angular2 application while utilizing the router.navigateByUrl method. Within my component, there is a function named goToRoute, structured as follows: router.goToRoute(route:string, event?:Event):void { if (event) ...

Setting the root directory and output directory can be a bit tricky when dealing with source code scattered across multiple folders. Here's

Utilizing TypeScript in my Node.js project, I previously had a directory structure that looked like this: node_modules src -Models -Routes -Middlewares -Controllers -index.ts package.json tsconfig.json In ...

Leverage the Node Short ID library in conjunction with Angular 6 using TypeScript

I attempted to utilize the node module within an Angular 6 typescript environment. Step one: npm i shortid Within my TypeScript class: import { shortid } from 'shortid'; let Uid = shortid.generate(); However, I encountered an error stating ...

Troubleshoot: Issue with injecting external component into another component using directive in Angular 2

I need the child component template to be loaded into the parent component template. (calling them child and parent for simplicity) Here is the child component: import {Component,Directive, ElementRef, Input} from '@angular/core'; import {IONIC ...

Using Angular's ngModelChange along with a button to reset the input field

In the backend, there is a text input that I use to search for data. Whenever something is typed into the input field, a clear button appears to reset the value of the field. Additionally, there is a log that shows the content of the input when characters ...

Expanding TypographyProps and TextFieldProps for enhanced functionality

Currently, I am developing a React component using TypeScript along with Material UI (MUI). The main purpose of this component is to display either an input field or text based on the mode selected. To switch between these modes, the prop mode is utilize ...

Is there a way to obtain asynchronous stack traces using Node.js and TypeScript?

When working with TypeScript, I encountered an issue with stack traces. It seems that only the bottommost function name is displayed. My setup includes Node.js v12.4.0 on Windows 10 (1803). Below is the code snippet: async function thrower() { throw new ...

Strategies for implementing searchbar filtering in Ionic3 and Angular5 data manipulation

I'm having trouble displaying product names on my search.html page based on the search bar input. I've tried using the Ionic searchbar component but it's not working. Can anyone help me with this issue? If there's an alternative solutio ...

Using ngControl in a custom validator directive can lead to a problem of cyclic dependency

I'm currently working on developing a custom Angular 2 validator directive and I'm looking to inject NgControl in the process. Here's an example of what I have: @Directive({ selector: '[ngModel][customValidator]', providers: [ ...

Integrate TypeScript into the current project

As a newcomer to Typescript, I am currently exploring the option of integrating it into my current project. In our MVC project, we have a single file that houses the definitions of all model objects. This file is downloaded to the client when the user fir ...

Here's how you can transfer the AceEditor value to the component state in ReactJS by utilizing the onClick event of a button

I'm facing a challenge implementing a customized CodeMirror using ACE Editor. I've experimented with incorporating state alongside the 'onClick' button parameter, but I haven't been successful in making it functional. import Rea ...

Exploring the capabilities of Angular 2.0.0 by testing a component integrated with a

Here's a code snippet of a component in Angular: import {Component, OnInit} from '@angular/core'; import {Route, Router} from '@angular/router'; @Component({ selector: 'app-index', templateUrl: './index.compone ...

Issue with displaying Ng-x spinner in Angular 5 function

Have you ever encountered this issue before? I've noticed that ngx-spinner doesn't work when used within a function, but it works fine when placed inside the subscribed callback. When placed outside of the authservice, the spinner isn't dis ...