Angular Form Group containing a Form Array will only submit a single object selected from a dropdown menu

My goal is to generate an array of objects based on the values selected from dropdown menus:

https://i.sstatic.net/pfe5n.png

For example, if 'John' from USA and 'Pablo' from Mexico are selected, the resulting array would be

[{person: 'John', country: 'USA'}, {person: 'Pablo', country: 'Mexico'}]
. However, only the last object is being submitted.

Check out the Stackblitz here

Answer №1

Issue arises from the fact that you are only creating a single FormGroup:

this.selectForm = this.formBuilder.group({
  persons: this.formBuilder.array([
    this.formBuilder.group({
      'person': '',
      'country': ''
    })
  ])
})

To resolve this, you should iterate through this.parts to dynamically generate them:

const persons = <FormArray>this.selectForm.get('persons');

this.parts.forEach((part) => {

  part.persons.forEach((person) => {
    persons.push(this.formBuilder.group({country: null, name: person.name}));
  })
});

This approach will result in two instances of FormGroup, each containing properties for country and name. It offers a more direct method than your current solution, making the code cleaner. Ensure to update the template accordingly.

Answer №2

If you find yourself in a situation where formControls are being duplicated instead of new ones being created within the ngFor loop, ensure that each form control has a unique name for every iteration to resolve this issue.

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

Angular 2 error: Unhandled Promise rejection stating that the template has parsing errors - the element 'login' is not recognized

I am currently attempting to implement Firebase Authentication login for an Angular2 project. However, I encountered the following error: Unhandled Promise rejection: Template parse errors: 'login' is not a known element: 1. If 'login&apos ...

What is the best way to integrate Next.js with Strapi (or the other way around)?

My goal is to develop an application utilizing Next.js for the frontend, fetching data from a Strapi API hosted on the same server. The plan is to have Strapi handle API and admin routes, while Next.js manages all other routes. I intend to use fetch in Nex ...

Utilizing EventEmitters for cascading operations in Angular 2 dropdown menus

I have a form with several cascading drop-downs - the selection in one drop-down determines the options available in the next. Each drop-down retrieves its values from an async data service, and Angular EventEmitter is used to handle events and populate su ...

Unable to select multiple checkboxes as they are unresponsive and not registering any clicks

I am facing an issue with rendering multiple checkboxes in a grid cell. I attempted to use formly multicheckbox, but unfortunately the checkboxes did not render properly. So I decided to try a different approach, however, now the checkboxes are not being c ...

Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on Gi ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Having difficulty handling text overflow in Angular4 and HTML

I'm facing an issue with displaying a very large text in a table. Despite trying various attributes such as - { text-overflow: clip; } { text-overflow: ellipsis; } { text-overflow: ellipsis-word; } { text-overflow: "---"; } { text-overflow: ellip ...

Error: Template Update Required Due to Observable Value Change - Fixing the ExpressionChangedAfterItHasBeenCheckedError

After searching through numerous SO posts in search of a solution, I finally stumbled upon one that involved a hacky implementation. The issue at hand involves an observable extracted from the ngrx store which I then subscribe to: this.navigationSelected$ ...

TypeScript was looking for 'never' but found an intersection instead

Can someone help me understand why a conflicting type intersection did not produce a type of never? What am I overlooking? type A = {value: string} type B = {value: number} type D = A & B type E<T> = T extends never ? 'never' : ' ...

Error message: The module '@microsoft/sp-build-web' could not be located

I am experiencing difficulties creating a SharePoint web part. In order to create the web part, the following libraries need to be installed: call npm install -g chalk call npm install -g loadash call npm install -g tar-fs call npm install -g update-notif ...

Steps for deploying an Angular 2 application without the need for a server

I am embarking on a basic Angular 2 project, however, I do not wish to manage it using npm. Is there any alternative method to initiate the project with the following steps: Compile all *.ts files Transfer compiled js-files to a separate directory (not ...

Sharing API data between components in Angular 5

Summary: I'm trying to retrieve data from an input field in a component form, then compare it using API services. After that, I want to take the value from the "correo" field in the form and pass it to another component. In this other component, I aim ...

Execute the installation of an Angular and Sprint Boot application on Azure Kubernetes by employing Docker containers and utilizing Azure Container Registry

I am currently exploring AKS, ACR, and DevOps Pipelines with the goal of setting up a CI/CD pipeline for my application that utilizes a Spring Boot backend and Angular frontend. Below is the Azure pipeline YAML file I am utilizing: # Deploying to Azure Kub ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

Getting Started with Angular 2: Choosing the Right IDE

After utilizing AngularJS 1.x for a few months, I have decided to transition to Angular2 with TypeScript. However, I am uncertain about which IDE would be best for this new venture. Additionally, I am unsure about the process of compiling TypeScript code ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

Limit the types of components allowed as children in a React component by utilizing TypeScript

I've been struggling with this question for a while, searching through answers but still unable to get my code to work. Here's the issue at hand. Within my code, I have a component called Steps which acts as a wrapper. I also have multiple Step ...