Adding dynamic values to nested form groups in Angular Form Array

After following a tutorial on creating a reactive form in an Angular application, I managed to implement it successfully. However, I encountered an issue when trying to add an additional control called "setNumber" to the form array. I want this control to auto-populate in the form based on the component iteration, instead of being manually inputted through the "name" and "gender" fields.

My StackBlitz code can be found here, in which I have included "setNumber" as its own input field within the form. While it works fine on my local machine, I am receiving a type error on StackBlitz. Despite this, the code functions as intended.

View the application screenshot here

Although I have tried using property binding to automatically populate the setNumber in the userArray within the component, I have not been successful so far. Any assistance in resolving this issue would be greatly appreciated!

Thank you

Answer №1

If you're facing a challenge, one possible solution involves updating your FormArray using a pipe. However, it's important to consider implementing the ControlValueAccessor interface to enable seamless communication between parent and child Forms without altering the data. Make sure to explore the capabilities of the IndexedFormPipe.

Check out this Stackblitz for more information.

Answer №2

I made some adjustments in your stackblitz to resolve the type errors. Specifically, I added form1: FormGroup in InputArrayComponent and made sure to address errors related to importing scss files.

If you simply need to pass the value of i+1 to the input component and set it as the value for the FormControl of "setNumber," you can add an Input() property in InputComponent (I named it index):

@Input() index: number;

In the InputArrayComponent template, you can then pass i+1 to the inputComponent like so:

<app-input [index]="i+1" [inputFormGroup]="$any(u)"></app-input>

To assign the value in ngOninit() for the inputArray, use the following:

this.inputFormGroup.get('setNumber').setValue(this.index);

Check out the updated stackblitz here:

https://stackblitz.com/edit/angular-ivy-2rwlwu?file=src/app/views/input/input.component.html

--- EDIT ---

After your comment regarding issues with deleting users and the index not updating, I implemented a set function to handle automatic index updates whenever the input changes:

@Input() set i(value: number) {
   this.index = value;
   this.inputFormGroup.get('setNumber')?.setValue(value);
};

However, please note that this approach may overwrite any user-made changes to setNumber. Alternatively, you can replace the input with a label displaying the index value, ensuring it remains visible but uneditable.

I've created a new version of the stackblitz with these modifications:

https://stackblitz.com/edit/angular-ivy-hhhz9m?file=src/app/views/input/input.component.html

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 does TypeScript provide me with insights even before compiling with tsc?

As I follow the instructions for incorporating TypeScript into my existing React Native project here, the final step instructs me to: Run yarn tsc to type-check your new TypeScript files. However, when I check VSCode, I am already receiving feedback from ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

"Authentication guard does not sit idle while waiting for the observable

My issue involves the auth guard service constructor(private _auth: AuthService, private _router: Router) { } canActivate() { if(this._auth.isLoggedIn()){ return true; } else { this._router.navigate(['/login']); ret ...

Combining two JSON arrays into a single array using Node.js

Two JSON arrays are available: var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{sec:'A', class_name:'xyz' ...}] I am looking to combine these arrays into a single array. var finalObj = [{id:1, name: 'xxx' ...},{i ...

Setting the value for a textbox using Jquery's .val() function works, while .attr() does not have the

//unable to get it working $("#TextBoxID1").attr("value","HI Value Change") //works perfectly fine $("#TextBoxID2").val("HI Value Change") <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type= ...

Sequelize Error: Cannot call User.hasMany as a function

I am experiencing a strange issue with my User and Client models. The User model has a relationship with the Client model, where User has many Clients. I am currently referencing the Sequelize documentation for associations at this link: Upon running the ...

Module-alias cannot be resolved by esm

Currently, I am utilizing the combination of esm package and module-alias. However, it appears that esm is not recognizing module-alias's paths. This is how I am loading my server file: nodemon -r esm ./src/index.js 8081 At the beginning of my inde ...

Methods for decoding a JSON object and iterating through its contents

After learning how to encode an object on the server side from this post, I am now interested in decoding it on the client side. Following is what I do on the client side: $.ajax({ type: "GET", url: "/cgi-bin/ajax_sort.pl", contentType: "appl ...

Issue with exporting member in VS Code but not in console

I currently have a NestJS project (project A) with one module that utilizes the @nestjs/typeorm and typeorm packages. In my other NestJS project (project B), I plan to use this module. However, there is a potential issue. Project B contains entities that ...

How can I send extra information along with my Ajax request in jQuery UI Autocomplete?

I currently have two jQuery UI Autocomplete widgets set up. The first autocomplete allows the user to enter a client's name, narrowing down options until the correct client is selected. A callback function then takes the ID of the chosen client and st ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Despite having a result, the Promise is returning an undefined value

In Vuejs, I have a method named getUsers that takes an array as input and fetches user data from the database. When calling it like this, it successfully returns the results: this.getUsers(executives).then( result => { this.speci ...

Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data: <template> <div> <h5>{{ title }}</h5> <div v-for="prop of data" :key="prop.id"> ...

Attempting HTTP requests on an iOS simulated device using Ionic Capacitor is not functioning properly

Upon sending an HTTP request, it functions smoothly on the browser (using Ionic serve). However, when I compile IOS and Android versions using Capacitor, I encounter the error displayed in the console: Error: SyntaxError: JSON Parse error: Unrecognized tok ...

Error message displaying "Invalid ID attribute in HTML 5 input"

On my website, I have a page with multiple items, each containing an HTML5 input field. Whenever a user changes the value of the input, it triggers an AJAX call to the server. The server then responds with JSON data, including an array of items that have ...

Can you extract debugging details from an ajax preflight inquiry?

I am currently working on a JavaScript project that involves making an AJAX request. However, I am encountering issues with the preflight OPTIONS call for this request failing. To provide some transparency to the user, I would like to display debug infor ...