Why is my formArray in Angular not validating or updating correctly?

I'm struggling to implement validation and updating for an array of form fields within my parent form group. Can anyone provide insight on what I might be missing?

My goal is to add a new 'Vendor Line' with multiple form fields and validate each of them individually. Currently, only the outer field of the formGroup is being validated. I want to extend this validation to cover each formArray field as well. My project is built using the ng-zorro framework from Ant. Any help is greatly appreciated.

Below is the code snippet:

new-project.component.html

<!-- Code snippet here -->

new-project.component.ts

// TypeScript code here

Answer №1

I was able to identify the root of the problem. It appears that even the nested forms need to be marked as dirty and updated. So, I made some modifications to the onSubmit function to address this issue. I appreciate the efforts of everyone who offered their assistance :)

submitForm(): void {
  // tslint:disable-next-line: forin
  for (const i in this.validateForm.controls) {
    this.validateForm.controls[i].markAsDirty();
    this.validateForm.controls[i].updateValueAndValidity();
    if (i === 'projectHeaders') {
      const control = this.validateForm.get('projectHeaders') as FormArray;
      // tslint:disable-next-line: forin
      for (const j in control.controls) {
        const controlTwo = control.controls[j] as FormGroup;
        // tslint:disable-next-line: forin
        for (const k in controlTwo.controls) {
          controlTwo.controls[k].markAsDirty();
          controlTwo.controls[k].updateValueAndValidity();
        }
      }
    }
    if (i === 'projectLines') {
      const control = this.validateForm.get('projectLines') as FormArray;
      // tslint:disable-next-line: forin
      for (const j in control.controls) {
        const controlTwo = control.controls[j] as FormGroup;
        // tslint:disable-next-line: forin
        for (const k in controlTwo.controls) {
          controlTwo.controls[k].markAsDirty();
          controlTwo.controls[k].updateValueAndValidity();
        }
      }
    }
  }
}

Answer №2

When utilizing Validators.required, the form status will be determined as either invalid or valid. If the required condition is not met, the field will be marked as invalid. The form will only be considered valid if the condition is satisfied. To indicate that a field is required, you can customize the validation message, change the border color to red, and disable the submit button.

In CSS::

input.form-control.ng-invalid {
    border: 2px solid red;
}
Your TypeScript file is correctly configured. Just remember to include a validation message or change the border color of the field if the required condition is not met.

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

checkbox with an option tag

I need help with implementing multi-select checkboxes inside an Angular 4 application. The checkboxes are not appearing next to the team names as intended. Can anyone assist me with this issue? Below is a snippet of my HTML code: <select class="form-c ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

Utilizing the subclass type as a parameter in inheritance

Looking for a way to restrict a function in C# to only accept classes of a specific base class type? In my current implementation, I have a base class (which can also be an interface) and n-classes that extend it. Here is what I am currently doing: abstr ...

Bringing PNGs and SVGs into React - Error TS2307: Module not found

While attempting to import PNGs/SVGs (or any other image format) into my React project, TypeScript presents the following error: TS2307: Cannot find module '../assets/images/homeHeroImage.svg' or its corresponding type declarations. The frontend ...

How to successfully extract and understand JSON data in Angular that has been delivered from a Spring controller

I am facing a unique challenge while trying to utilize JSON data obtained from a Spring API to populate a list in Angular. Within the datasets-list.component.ts file, I have the following code: import { Component, OnInit } from '@angular/core'; i ...

Utilizing Prisma Enum with Nest JS: A Comprehensive Guide

While working on my backend with Prisma and NestJS, I have encountered an issue. I defined an enum in Prisma that works fine in debug mode, but when I generate the Prisma client using nest build, I get an error. Object.values(client_1.RoomSharingType).join ...

There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables like Arrays

My route.js const express = require('express'); const router = express.Router(); const University = require('../models/university'); var mongo = require('mongodb').MongoClient; var assert = require('assert'); va ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

Attempting to render the application results in an error message stating: "Actions must be plain objects. Custom middleware should be used for asynchronous actions."

I am experiencing an issue while testing my vite + typescript + redux application to render the App component using vitest for testing. I am utilizing redux@toolkit and encountering a problem when trying to implement async thunk in the app component: Error ...

Is it possible to utilize CreateSpyObj to generate a spy for every method within a given class?

I am in the process of creating unit tests for my Angular application and I am exploring the usage of spies. Currently, for each service utilized by my component, I find myself writing code similar to the following: let fakeMyService = jasmine.createSpyO ...

Encountering an error during the building of an AOT compilation due to a jointly used

After creating a shared angular 2 module to organize reusable components, everything was functioning properly. However, the issue arose during the AOT build process with the error message provided below: Error encountered resolving symbol values staticall ...

strictNullChecks and the dissemination of null values

Considering implementing the strictNullChecks flag in a large code base presents some challenges. While it is undeniably a valuable tool, the abundance of null types in interface definitions may be impacting the code's readability. This is particularl ...

What is the best way to initialize a component only when its tag is set to *ngIf=true?

Update: After receiving a very helpful answer from Günter Zöchbauer that resolved my issue, I still have a lingering question about the correct approach for achieving the desired result. The context is provided below. With my custom tag on the parent ...

Display only the clear button within the p-calendar element

I am struggling to make a Clear button appear only on the p-calendar component. myComponent.html <p-calendar value="#{property.propDate}" id="date" [showIcon]="true" [utc]='true' placeholder="{{ timePickerPlaceHolder }}" [showTrans ...

Enforcing strict property validation on variables passed into TypeScript functions

Is there a method to enforce excess-property checking, not only for an inline object literal but also one derived from a variable? For instance, let's say I have an interface and a function interface Animal { speciesName: string legCount: nu ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

Tips for organizing HTML logic in a separate document

I am faced with the task of displaying a list in HTML based on specific conditions: <!-- Display list if there are more than 5 results --> <div list.numberOfResults > 10"> <b>Name: </b>{{list.name}} <b>ID ...

Ways to eliminate the need for margin adjustments when buttons are shown in Responsive mode

I am currently utilizing Angular 14 along with SCSS Within a dialog component, I have two buttons displayed horizontally. The first button displays the text I am feeling lucky, while the second button displays Not lucky. There should be a separation of 20 ...

Issue encountered: Compilation error occurred following the update from Angular 11 to Angular 15, stemming from the module build failure within the sass-loader directory

I recently attempted to update angular from version 11 to 15, but encountered an error as shown in the screenshot below ./src/assets/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: expected "(". ...