Steps for identifying if a FormGroup contains a child control that is marked as INVALID and has been TOUCHED

When discussing Reactive Forms, the query arises about determining if a FormGroup contains a child control that is both invalid and touched, without having to inspect the entire structure of the FormGroup.

The issue lies in how the FormGroup becomes marked as touched once any of its children are touched, and is labeled as invalid as soon as any of its children are deemed invalid. However, there seems to be no straightforward method to check for a child that meets both criteria: being invalid and touched.

In essence, the goal is to accomplish this task without manually traversing through the FormGroup:

function traverseFormGroup(formGroup: FormGroup): boolean {
  let hasErrors = false;

  for (const key of Object.keys(formGroup)) {
    const child = formGroup.get(key);

    hasErrors = child instanceof FormGroup || child instanceof FormArray
      ? hasErrors || getFormValidationErrors(child)
      : hasErrors || !!child && child.errors !== null && child.touched;
    
    if (hasErrors) {
      return true;
    }
  }

  return hasErrors;
}

Answer №1

validateFormControls(formGroup: FormGroup | FormArray) {
Object.keys(formGroup.controls).forEach(field => {
  const ctrl = formGroup.get(field);
  if (ctrl instanceof FormControl) {
    ctrl.markAsTouched({ onlySelf: true });
    ctrl.markAsDirty();
    ctrl.updateValueAndValidity();
  } else if (ctrl instanceof FormGroup || ctrl instanceof FormArray) {
    this.validateFormControls(ctrl);
    ctrl.markAsTouched({ onlySelf: true });
    ctrl.markAsDirty();
    ctrl.updateValueAndValidity();
  }
});

}

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

Exploring how to successfully test the parsing of a string using JSON.parse in Jest

Currently, I am in the process of creating unit tests for an API. In a scenario where I implement the following code: const apiResponse:object = JSON.parse(body) expect(apiResponse).toHaveProperty('error') If the API does not return JSON data, ...

Angular Material autocomplete options are obscured by browser autofill suggestions

I am facing a challenge in Angular Material where the material autocomplete feature is functioning properly, however, the browser's autofill options are causing an overlap with the material autocomplete popup. Is there a way to disable autocomplete fo ...

It is feasible to completely override a class in TypeScript

I have a subclass defined as follows: customException.ts /** * Custom Error class. * * @class Error * @extends {Error} */ class Error { /** * @type {string} * @memberof Error */ message: string; /** * @type {boolean} * @memberof ...

Exploring nested items within a JSON array using Angular 2

While there are numerous answers out there on how to iterate over JSON items in Angular 2, I'm currently struggling with this particular issue: { "datesofinterest": [ { "name": "Holidays", "year": "2017", "version": ...

No gripes about incorrect typing when extending interfaces

I tried out the following code snippet here interface OnlyName { name: string } interface MyTest2 extends OnlyName { age: number } let test1: OnlyName; const setTest1 = (v: OnlyName) => { test1 = v console.log(test1) } let test2: My ...

To set up Ionic on your project, run the command `npm install

After setting up a new Ionic project, I included the Android platform using the command ionic cordova platform add android. This action added the following entry in the config.xml file: <engine name="android" spec="~6.1.2" /> Prior to this, I came ...

Having trouble getting Jest transformers to play nice with a combination of Typescript, Webpack, and PEGJS

In my current NPM project: { "scripts": { "test": "jest --config=jest.config.js" }, "devDependencies": { "@types/pegjs": "0.10.3", "@types/jest": "29.1.1", ...

Solving the Path Dilemma in TypeScript Functions within the Firebase Environment

My Firebase project utilizes TypeScript functions with the following directory structure: - functions - src - index.ts - shared - other.ts - tsconfig.json - package.json Within my tsconfig.json file, the configuration is as follows: { &q ...

Tips for adding an extensive collection of fixed attributes to a function using Typescript

I am attempting to write a function that includes a lengthy list of static strings attached as properties, all returning the property as a string value: const arr = ["a", "b", "c"]; // there are around 140 items in the actual list const f = (tag: strin ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

Upgrading Angular1 components with NgUpgrade becomes a challenge due to the restriction on using templateUrl

Looking to enhance an ng1 component for use within an ng2 component. When utilizing a template string with the ng1 component, it upgrades successfully. However, when switching to templateUrl, the application crashes and throws the following error: angula ...

What is the best way to eliminate existing double quotation marks within string values stored in objects in Angular?

When using Angular, data is retrieved in object form from the database to the backend and then to the frontend. Here's how it looks in HTML: <h3>Payslip for the month of {{dataout[0].MonthYear | json }}</h3> The issue arises when running ...

Sending Information to Child Component in Angular2

Hi there, I'm currently facing an issue with passing data from a parent Component to a child component controller. Here is the markup code of my parent Component parent.component.html <element [mydata]="Value"></element> By using this ...

Module 'xlsx' cannot be located

I encountered this issue while building with Jenkins on the server, but it works fine on my local machine without any errors: 15:07:39 "", 15:07:39 "", 15:07:39 "ERROR in src/services/excel.service.ts:2:23 - error TS2307: Cannot find module 'xlsx&apos ...

Update the component with the current route and state synchronization with react router dom

Is there a method to synchronize the active route in the browser with the component state? When I click on "Route 2" in the navigation bar, it gets highlighted as the active route and the browser URL shows "/route2". However, upon refreshing the page, "Ro ...

NextJS applications can encounter issues with Jest's inability to parse SVG images

Upon running yarn test, an unexpected token error is encountered: Jest encountered an unexpected token This typically indicates that Jest is unable to parse the file being imported, suggesting it's not standard JavaScript. By default, Jest will use ...

Angular 7 filtering system for searching within complex nested objects

Within my Angular 7 application, I am encountering the following JSON data in a nested structure. I have successfully displayed this data using *ngFor. JSON [ { 1: [ { "name" : "A" }, { "name" : ...

The issue of binding subjects in an Angular share service

I established a shared service with the following Subject: totalCostSource$ = new Subject<number>(); shareCost(cost: number ) { this.totalCostSource$.next(cost); } Within my component, I have the following code: private incomeTax: num ...

Since making the switch from Angular 5 to 6, I've been consistently encountering a frustrating issue: the error message "timers in xml2js cannot

As mentioned in the title, I am constantly encountering a strange error. Despite attempting to uninstall it using npm uninstall xml2js, nothing has proven effective thus far. https://i.stack.imgur.com/DccM7.png ...

Managing checkbox selection in a recursive dynamic Angular component

Currently, I am encountering an issue with the parent checkbox functionality. When I select the parent checkbox, all of its children are also selected. However, if I uncheck a child checkbox, it does not affect the parent checkbox selection. I am looking ...