Troubleshooting issues with setting errors on a FormGroup instance in Angular Reactive Forms are proving to be more challenging

Currently I am working with Angular 4.4.3 reactive forms to create custom validation for a group of controls within a form. As per the documentation on AbstractControl.setErrors, this method updates the errors property of the AbstractControl that it's called upon, and also updates the status of its parent. However, it does not update the parent's errors property. My goal was to set the errors property on a FormGroup instance by using the inherited setErrors method from FormGroup. Surprisingly, it did not update the errors as expected.

Below is a snippet of my code: When trying this approach on FormControl instances, it successfully updates their errors along with their parents' validity status (although the parents' errors remain unaffected):

let myFormGroup 
    = this._formBuilder
          .group({
                   ctrl1: [null],
                   ctrl2: [null]
                 }, 
                 {
                   validator: (fg: FormGroup) => {
                                   let ctrl1 = fg.get('ctrl1'),
                                       ctrl2 = fg.get('ctrl2'),
                                       ctrl1Empty = !ctrl1.value,
                                       ctrl2Empty = !ctrl2.value;

                                       //Successfully sets ctrl1.errors and fg.status, but not fg.errors 
                                       if (ctrl1empty)
                                         ctrl1.setErrors({ctrl1required: true});
                                       //Successfully sets ctrl2.errors and fg.status, but not fg.errors 
                                       if (ctrl2Empty)
                                         ctrl2.setErrors({ctrl2required: true});
                                       //Doesn't work, doesn't update fg.errors
                                       if (ctrl1Empty && ctrl2Empty)
                                         fg.setErrors({required: true});
                              }
                 })

Any insights on why this might be happening?

Answer №1

After receiving confirmation from @incognito, I was able to pinpoint the issue upon closer examination.

Although setErrors does indeed set the errors property of the form group instance, the custom validator mentioned in my initial query did not explicitly return a value (i.e., a falsey undefined value). Upon delving into the reactive forms module code within Angular, I came across this method. In this method, errors raised by various validators are merged at this line, where it checks if errors (undefined in my code snippet) are not equal to null. This particular condition, when evaluated in its es5 version, results in false, culminating in a null outcome and hence disregarding the contents of the errors property defined in the code. The valuable lesson learned here is: always ensure custom validators return a value, even if subsequent nested FormGroup instances have their own customized logic for error handling.

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

Problem with Ionic 2 checkboxes in segment controls

I encountered an issue with my screen layout. The problem arises when I select checkboxes from the first segment (Man Segment) and move to the second segment (Woman Segment) to choose other checkboxes. Upon returning to the first segment, all my previous ...

Encountered an error while attempting to upgrade to the latest @angular/cli version 1.0.0: Unexpected symbol "<" found in JSON at the beginning of the file

When I was using angular-cli 1.0.0 beta 23, my service was able to fetch a local JSON file for testing without any issues. However, after upgrading to angular/cli 1.0.0, I encountered the following problem: GET http://localhost:4200/json/inputInventory/ ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

Building upon a React component with TypeScript, we are extending its functionality using a generic type and then leveraging this same generic type

In my component, I have a setup where it takes two props - node and patchCurrentNode. import { css } from '@emotion/react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import React, { PropsWithChildren, useStat ...

Refreshing the PrimeNg Organization Chart through code executionPrimeNg Organization Chart

Using the p-organizationChart to display hierarchy, I encounter an issue where dynamically added child nodes do not display the expand arrow until I select a Node. Therefore, I am seeking a way to programmatically refresh the org-chart. Any suggestions on ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

Do not begin the next task until the current function has properly concluded

I am currently developing a project in Ionic v4 with Angular that involves using BLE to communicate with a Raspberry Pi. The project consists of several steps: Searching for devices around me Connecting to the desired device Activating notifications Sen ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

Utilizing type arguments in JSX components when applying withStyles

When working with React and material-ui, I am attempting to create a JSX component that can accept generic parameters while also utilizing the withStyles Higher Order Component (HOC) to inject styles. The initial approach looked something like this: cons ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

What are the steps to enable full functionality of the strict option in TypeScript?

Despite enforcing strict options, TypeScript is not flagging the absence of defined types for port, req, and res in this code snippet. I am using Vscode and wondering how to fully enforce type checking. import express from 'express'; const app ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

The document type is not compatible with the element "BR" in this location; it is assumed that the "LI" start-tag is missing

How can I create a validated list with HTML 4.01 standards? I tried the following code, but it's giving me an error: "document type does not allow element 'BR' here; assuming missing 'LI' start-tag" <tr> <td colspan="2" ...

Guide on upgrading an Angular project to a targeted version with its corresponding dependencies

I'm embarking on reviving a previous angular venture. My objective is to bring it up-to-date with a particular version along with upgrading all its affiliated dependencies to the most recent ones. I attempted by initially uninstalling the CLI version, ...

Ways to transfer a value between two different card elements

I have designed a component with three div cards side by side using bootstrap. The first card displays a list of products, and my intention is that when a product is clicked, the details should appear in the second card on the same page. However, this fun ...

Tips for efficiently passing TypeScript constants to Vue templates without triggering excessive reactivity

I'm curious about the most efficient way to pass a constant value to a template. Currently, I am using the data property in Vue, but I believe that is better suited for state that changes over time as Vue adds event listeners to data properties. The c ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

Organizing Firebase functions: Managing multiple functions and dependencies

Objective I aim to gain a deeper understanding of how the firebase CLI manages the deployment process for multiple firebase functions, each stored in different files, and how it handles dependencies that are specific to certain functions. Situation If I ...