Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data:

This is what my form builder setup would be like :

constructor(private formBuilder: FormBuilder) { 
    this.userForm = this.formBuilder.group({
      'inputOne': ['', [Validators.required]],
      'inputTwo': ['', [Validators.required]],
       ...
      'inputN': ['', [Validators.required]]
    });
  }

And this is how my template structure would look like :

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="item.name">
      </div>
</form>

The items are fetched dynamically from the backend

Question: How can I populate controls dynamically in Angular reactive forms?

Answer №1

It seems like a form array would be more suitable in this scenario, rather than a group...

  constructor(private formBuilder: FormBuilder) { 
    // Initialize an empty form array
    this.userForm = this.formBuilder.array([]); 
  }

  // Use this method whenever you want to add an item to the array
  private addItem(item) {
    // Create a control with specified validators and values
    const fc = this.formBuilder.control(i.lastName, [Validators.required]);
    this.userForm.push(fc); // Add the control to the form array
  }

  // Call this function whenever you need to reset the form array
  private resetFormArray(items) {
    this.userForm.clear(); // Clear the existing array
    items.forEach(i => this.addItem(i)); // Add the new items
  }

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
    <label for="lastName">{{item.name}}</label>
    <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="i">
  </div>
</form>

Please note that the index is being used as the form control name in this implementation

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

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

Combining AngularJS, D3, and JQuery on a single webpage can pose challenges, specifically with D3's ability to accurately read DOM dimensions

I am encountering an issue with my webpage not loading properly. I have structured it using a simple header-body-footer layout in html5 and CSS3. +----------+ | HEADER | +---+----------+---+ | BODY | +---+----------+---+ | FOOTE ...

Is there a way for me to understand the connection between `FormsModule` and `ngModel`?

After following the tutorial on angular hero editor, I came across a puzzling issue regarding FormsModule. It seems that the demo does not function properly without importing FormsModule first: https://angular.io/tutorial/toh-pt1#the-missing-formsmodule ...

What are some strategies for safeguarding a disabled button?

Is there a way to securely disable a button if the user does not have permission to access it? I currently disable it at the Page_Load event: Page_Load() { if(!userhasrights) { btn.Enabled=false; } } However, after rendering, ASP.N ...

Using the val() function on a select element can occasionally result in a null value

Having an issue with my select. For some reason, when I use $(".test").val(), it sporadically returns null. Can't seem to figure out what's causing this inconsistency. console.log($('.test').val()); <script src="https://ajax.googl ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Why does the Material button style take time to apply when my Angular application first loads instead of being immediate?

Inside the Angular application I'm working on, there is a toolbar component that consists of three different links. The first link directs to the main app page, while the other two lead to distinct components within the app. Each link is styled with c ...

Is there a way to make a <div> load automatically when the page starts loading?

I'm having an issue with my code where both <div> elements run together when I refresh the page. I want them to display separately when each radio button is clicked. <input type="radio" name="cardType" id="one" class="css-checkbox" value="db ...

Unlocking the potential of input values in Angular.jsDiscovering the secret to

I'm currently experimenting with the angular date picker directive. My goal is to retrieve the entered date value from the date picker and log it to the console. However, all of my attempts so far have been unsuccessful. Here's a snippet of my c ...

Having trouble adding flexslider before a div element with jQuery

Hey there! I recently got flexslider from woothemes.com. The page structure I'm working with looks something like this: <div class="parentdiv anotherdiv"> <div class="child-div1">some buttons here</div> <div class="child-div2"& ...

The kendo-angular-chart is missing the required dependency kendo-charts-1.19.1.tgz

Is anyone else experiencing issues with the kendo-chart installation? I am attempting to install kendo-angular-chart and encountering the following problem: npm install npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@progress/ ...

Jquery adds a fun, wobbly effect to animations

I'm experiencing an issue with the animation I've implemented causing some slight shaking and wobbling of the text and certain elements which is affecting the overall look. You can view a live example of this behavior here: This problem specific ...

Animating an image inside a bordered div

I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div. ...

Is there a way to automatically refresh random data from the server to the web client without the need for manual browser refresh?

Looking to send random data from the server to the web client without reloading the browser? Well, I've got you covered. Using a combination of web framework express.js, template engine pug.js, socket.io, and jQuery, you can achieve this seamlessly. ...

What is the mechanism by which Redux sends state to mapStateToProps?

I'm currently delving into the inner workings of React and Redux, and recently came across FuelSavingsPage.js in this sample project. While I grasp how actions is obtained in mapDispatchToProps, I am uncertain about how state is passed to mapStateToPr ...

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

Prevent unexpected page breaks in <tr> elements on Firefox (Could JavaScript be the solution?)

Wondering if there are any ways, possibly through JavaScript or CSS, to avoid having page breaks within <tr> elements specifically in Firefox. Given that FF does not yet fully support page-break-inside, I assume this might need to be addressed using ...

React is currently in the process of downloading images that were not fetched during

(Update: Initially, I suspected React Router was the cause of this issue. However, after eliminating React Router from the codebase, the problem persists. Therefore, I have extensively revised this inquiry.) Situation: I am dealing with paginated pages th ...

What is the best way to recreate WordPress categories using static HTML pages?

As I consider converting my WordPress website to static HTML pages, I'm planning on editing them in tools like Responsive Site Designer, Dreamweaver, or SublimeText. My main concern is how I will organize content into categories without the convenien ...

What is the method for transferring form data to a different page?

Currently utilizing AngularJS version 1.5.6 and looking for guidance on properly passing form data using $location.path. Below is my code snippet for Page A: <form> ... <button type="submit" ng-click="submit(formData)"> ...