Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form:

form: UntypedFormGroup;

this.form = this.fb.nonNullable.group({
  f1: [''], f2: this.fb.nonNullable.array([], Validators.required),
  f3: this.fb.nonNullable.array([]), f4: this.fb.nonNullable.array([]),
  f5: this.fb.nonNullable.group({ id: ['', Validators.required] })
});

Upon resetting the form, I noticed that the required validator for the id field remains unchanged.

In a previous project using Angular 14 without any nested formgroup, I was able to reset the form completely with this.form.reset(). However, in this case, the valid state of the id field persists as false.

Is there a solution to this issue? Additionally, even though I have specified that the formgroup and formarray should not allow NULL values, the array fields are still initialized as NULL.

Current Approach:

this.form.reset();
console.log("Form after reset:", this.form.value);
console.log("Id field valid? ", this.form.get('f5').valid);

Current Result:

Output 1: Form after reset: {"f1":"","f2":[null],"f3":[],"f4":[],"f5":{"id":""}}
Output 2: Id field valid?  false

NOTE: The value of the f2 field has been set to NULL, hence its presence in the output.

Expected Outcome:

Output 1: Form after reset: {"f1":"","f2":[],"f3":[],"f4":[],"f5":{"id":""}}

In the expected output, the form should reset to its initial state while maintaining the validation status of the mat-form-field linked to the id field. This will be indicated by the red coloration of the field.

Answer №1

As stated in the official documentation, when the control's value is reset with the reset() function and the nonNullable property is set to true, the value will revert back to its initial state if available. However, it's important to note that setting nonNullable to true does not guarantee that the value will never be null, falsy, or invalid after the reset operation.

The Validator.required() documentation explains that an empty field value will result in an 'invalid' state. An example is provided for a zero-length string:

const control = new FormControl('', Validators.required);
console.log(control.errors); // {required: true}

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

How can I find a user's ID in a JSON file using for...in loop in Discord.js?

I'm facing an issue with this loop where I am only able to retrieve the guild id instead of the user id that I actually need. Here is my code: for(let userID in money){ res.push({"guildid": message.guild.id, "id": userID, " ...

I am looking to save a collection of variables in an array and store it as a $_SESSION variable

Looking to store an array of variables as a $_SESSION variable in order to use it in another .PHP file and perform operations with it. The array: <script> var idArray = [18, 28, 31, 38, 41]; </script> What I attempted, but didn't suc ...

Creating a text box that stands out by adjusting the length in Bootstrap

My webpage displays three text boxes, and I want to increase the size of one specific text box. Here is the code that I have tried: <div class="row"> <div class="col-md-3"> <mat-form-field (keydown.enter)="$event.preventDefa ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

Tips on increasing the width of the 'select' option once the user decides to make a selection

Here's a question for you: I have a <select> box where I set the width to 120px: <select style="width: 120px"> <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option> <option>ABC</option> < ...

What is the best way to change the `this` type of an object that is provided as a parameter to a function

I am looking to create a custom function that can expose certain properties to the this of an object being passed as an argument. For example, this is how the function would be called: const props = ['bar']; myBarFunction(props, { get foo() { ...

execute function following ng-repeat

I'm diving into Angular for the first time and I want to start with a simple example. After using ng-repeat to display some data, I'd like to manipulate that data with JavaScript functions. However, I'm not sure when to trigger the JavaScri ...

Using Jquery colorbox to redirect or forward within the current colorbox container

I am facing a challenge with a colorbox that is currently loaded. I am looking for a way to redirect or forward to another page within the existing colorbox. window.location = href; does not seem to be effective in this situation. EDIT: To be more precis ...

What is the best way to transfer JavaScript if conditions to an external file?

I am currently working on a script to transfer data between various software applications. Within this script, there is an if condition set up to ignore specific fields that are not required for the transfer process. The condition in question looks somethi ...

How can PrimeNG PIE chart values be displayed by default instead of only on hover over the slice?

front end <td> <div class="p-col-8 ui-toolbar-group-right"> <button pButton type="button" icon="pi pi-search" (click)="populate_charts()"></button> </div> </td> TS-File ...

Class variable remains unchanged following AJAX request

Upon completion of the ajax request, two integers are received - this.N and this.M. However, these values are not being set by the storeDims() function even though the correct decoding is done on the dims variable. This implies that I am unable to access ...

During the build process, NextJS encountered an issue locating the constants.js module

I encountered an error while executing next build using next version ^10.2.3. I attempted to remove the node_modules and .next folders, then reinstalled dependencies with npm install && next build, but the issue persists. Error: Cannot find mod ...

Axios error in Express middleware - unable to send headers once they have been processed

I can't seem to figure out why my code is not running correctly. While using Axios in my middleware, I am encountering this error message: Error: Can't set headers after they are sent. This is the snippet of my code (utilizing Lodash forEach): ...

When using ng-repeat with Angular ui-bootstrap and tabs, the new tab will not be selected if there are no existing tabs present

To showcase the problem I'm facing, please refer to this link: http://codepen.io/pietrofxq/pen/ZLLJdr?editors=1010 Click on "remove tabs" and then on "add tab" The challenge at hand involves using a loop with ng-repeat to display tabs. At times, the ...

Utilizing Vue.js to apply conditional statements or filters on v-for generated outputs

Currently, I am working on organizing my results by category. I believe there is room for improvement in the way it's being done: <div><h2>Gloves</h2></div> <div v-for="stash in stashes" :key="stash.id"> <div v-for= ...

Creating a JSON utility type for an already existing type, such as JSON<SomeExistingType>

Is there any tool or utility available that can accomplish this task? const foo: Foo = { ... } const bar: string = JSON.stringify(foo) const baz: JSON<Foo> = JSON.parse(foo) JSON<Foo> would essentially mirror all the properties of Foo, with th ...

Extract HTML content using CKEditor

Hey there! I'm in need of some help with getting user-entered data from a textarea. I've already attempted using CKEDITOR.instances.editor1.getData() and CKEDITOR.instances.ckeditor.document.getBody.getHtml(), but unfortunately both only return ...

transforming PDF into an Image using PhantomJS

Currently, I am using PhantomJs to convert webpages into images successfully. Here is the code snippet I am using: phantomjs.exe rasterize.js http://myurl.com/mypage/ out_put_image.png Even though this method works well for webpages, it encounters an iss ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...