What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question!

I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example of what I mean by visiting this link: ionic page with repeated forms. To help clarify the placement of the input spaces, I labeled them as "input3," "input4," and so on.

The number of these forms displayed on the page is determined by the user through a settings modal, which means I cannot hard-code them statically into the HTML markup. In order to achieve this dynamic functionality, I utilized the following code snippet in my HTML:

      <form>
      <ion-row *ngFor="let y of rowCount|times" text-center align-items-center>
          <ion-col align-self-center col-2>{{y}}</ion-col>
          <ion-col text-center align-self-center col-4><ion-input id='input{{y}}' 
            formControlName="input{{y}}" [(ngModel)]="inputy"></ion-input></ion-col>
          <ion-col align-self-center col-4>{{status}}</ion-col>
          <ion-col align-self-center col-2><button
            id= 'button{{y}}' ion-button small icon-only>
            <ion-icon name="brush"></ion-icon></button></ion-col>
      </ion-row>
    </form>

To repeat the rows based on the value stored in the variable rowCount, I implemented a Custom Pipe named times.

While I was successful in dynamically generating attributes such as id, formControlName, and ngModel within the HTML, I am facing a challenge in accessing these dynamically created values from the TypeScript file associated with this component. Can you provide guidance on how I might retrieve the values of each dynamically generated formControlName in the TypeScript code? Additionally, is there a way to extract the values from the dynamically generated ngModel?

Answer №1

It seems like you might be blending reactive forms, such as using formControlName, with template driven forms like ngModel. It would be beneficial to review the Angular documentation on these concepts before proceeding.

If you opt for reactive forms, consider utilizing a formArray as it is specifically designed for this purpose. The ngFor directive allows you to access the index in the template, and your formControlName will correspond to the index.

You can update the value of reactive forms using methods like patchValue and setValue from your TypeScript file.

I'm not implying that you must choose reactive forms over template driven forms; just avoid mixing them together. If you feel more comfortable with template driven forms, that's perfectly acceptable. The documentation provides an overview of the advantages and disadvantages of each approach.

Best of luck!

Answer №2

Success! I was able to accomplish my goal.

In the file home.ts, I established a FormArray within a FormGroup, as illustrated below:

  this.homeForm = new FormGroup({
  bicos: new FormArray([])
  });

Next, in your repeat/add function, you will utilize this code:

 addForm(){
 (<FormArray>this.homeForm.controls['bicos'])
 .push(new FormControl(null));
 }

Moreover, in home.html, the crucial section appears like this:

 <form [formGroup]="homeForm"> 
 <ion-row formArrayName="bicos" *ngFor="let item of 
 homeForm.controls.bicos.controls; let i = index" >
 <ion-col text-center align-self-center col-5>
 <ion-input #inputs formControlName="{{i}}" type="number"></ion-input>
 </ion-col>
 </ion-row>
 </form>

Reiterating what I mentioned in the previous comment, you can also refer to another approach here.

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

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

What would cause the nsfw property to be absent from a TextChannel in client.on("messageCreate") event?

Currently working with Typescript in combination with Discord.js v14, I'm encountering the following error: Property 'nsfw' does not exist on type 'DMChannel | PartialDMChannel | ... Below is the snippet of problematic code: client.on( ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

Leveraging multer for handling a FormData object in a node.js server

Having trouble with an HTML form that includes two buttons among other text input areas. The front-end javascript code is set up to handle the submit action by creating a FormData object to store the file and sending it via a jQuery AJAX request to a node. ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

Invalidating Angular Guards

My goal is to have my auth guard determine access privileges using an observable that periodically toggles a boolean value. My initial approach was as follows: auth$ = interval(5000).pipe(map((n) => n % 2 === 0)); canActivate( next: ActivatedRoute ...

Difficulty encountered when deploying cloud function related to processing a stripe payment intent

I've been troubleshooting this code and trying to deploy it on Firebase, but I keep running into a CORS policy error: "Access to fetch at ... from origin ... has been blocked by CORS policy." Despite following Google's documentation on addressin ...

The callback function is not being executed in the Ajax request

$(document).ready(function(){ var requestURL = 'http://www.football-data.org/soccerseasons?callback=?'; $.ajax({ type: 'GET', dataType: 'json', url: requestURL, success: function(data){ cons ...

Set the rowspan to 2 when the v-for index does not equal 2

This is the table I am working with: <table class="table table-condensed table-sm table-striped table-bordered" id="list"> <thead> <tr> <th v-for="(column, index) in columns" :key=& ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

What is the best way to enable multiple form submissions in web2py?

Fortunately, web2py has a built-in feature that prevents multiple form submissions by utilizing a hidden _formkey value. Typically, when a form is submitted, the page is reloaded and a new key is generated. However, in my case, I am submitting the form usi ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Issues with React in a Production Environment

After successfully developing a react app and express API that worked correctly in localhost, I decided to move my API to a digitalocean droplet. The droplet only had an IP address and used HTTP. While utilizing the API from the react app in development m ...

Swap out a button for another using JavaScript

I am facing a challenge where I need to replace an active button with a deactivate button. The issue is that when I click on the active button, it does change to the deactivate button as expected. However, clicking again does not switch it back to the acti ...

Tips for minimizing Angular $digest-cycle invocations

Issue In my application, I have noticed that some callbacks are being called excessively during the $digest cycle. This high frequency of calls is causing performance concerns as these callbacks are triggered way more times than expected, sometimes even e ...

The element 'loginToken' is not found within the type '{ loginToken: string; } | { error: Error; } | { username: string; password: string; }'

I'm currently working on creating a reducer using Typescript and Redux, but I keep running into this error: Property 'loginToken' is not recognized in type '{ loginToken: string; } | { error: Error; } | { username: string; password: str ...

Issue with Axios response processing

I need to upload a new document into a database using Axios in React. I have successfully implemented the functionality, but I also want to display a message in the console saying "New post has been inserted". This is my front end code: newTodo(todo){ ax ...

A more efficient approach to creating a personalized design

After realizing the original question was unclear and wouldn't solve my problem, I have decided to edit it and create a new one. For my project, I require a customized layout where users can move, resize, add, or remove each box according to their pr ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Error: Unexpected TypeError occurred stating that 'map' cannot be read from undefined, although the map method is not being used in the code

I have recently developed an Ethereum application for conducting transactions using React and the ethers module. Below, you can see a snippet of my code, specifically focusing on the function sendTransactions: import {ethers} from 'ethers'; impor ...