Tips for addressing the issue of FormControlName being duplicated for every row in reactive forms

My reactive form contains columns and rows that can be dynamically added. However, when inspecting the form and adding multiple rows, the formControlName attribute repeats for each row.

I am looking for a solution to have incrementing formControlNames for the columns of each row.

For example:

row 1 -> two columns (formControlNames --> 0, 1)

row 2 -> two columns (formControlNames --> 0, 1)

desired outcome:

row 1 -> two columns (formControlNames --> 0, 1)

row 2 -> two columns (formControlNames --> 2, 3)


I have already implemented some workarounds, but the issue persists where the formControlNames are being updated for all rows and the last added formControlName is applied to all rows.

Here is a snippet of the HTML code:

<form [formGroup]="rubricForm">
    <table class="table mt-5">
        <thead>
            <tr>
                <th></th>
                <th class="tableHeader" scope="col" formArrayName="scoreHeaders" *ngFor="let col of scoreHeaders.controls; let i = index"><input pInputText type="text" 
                    [formControlName]="i"></th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let col of leftHeaders.controls; let i = index">
                <th formArrayName="leftHeaders" scope="row">
                    <span>
                        <input pInputText type="text" name="criteria-field" placeholder="Enter Criteria" [formControlName]="i" required />
                    </span>
                </th>
                <td formArrayName="cells" *ngFor="let col of cells.controls; let j = index">
                    <textarea pInputTextarea name="criteria-val" [cols]="30" [rows]="5" [formControlName]="setFormControlName()"></textarea>
                </td>
            </tr>
        </tbody>
    </table>
</form>

And this is the corresponding Typescript function:

setFormControlName(): any {
    let leftHeaderLen = this.leftHeaders.length;
    let scoreHeaderLen = this.scoreHeaders.length;
    let result = 0;
    if (leftHeaderLen === 1 && scoreHeaderLen === 1) {
      result = 0;
      return result;
    }
    else {
      result = (leftHeaderLen + scoreHeaderLen) - (leftHeaderLen + 1);
      console.log(`inside second loop ${result}`);
      return result;
    }
  }

You can find the complete code in the links provided above. Thank you in advance for your help!

Answer №1

Dealing with Reactive Forms can be complex, but I will provide a solution later on. In the meantime, I recommend using ngModel instead of ReactiveForms.

It's clear that you need to manipulate data in two dimensions.

Let's start with the initial state:

top = [];
left = [];
data = [[]];

We require logic for adding both rows and columns:

addColumns() {
    this.top.push('');
    this.data.forEach((row) => {
      row.length < this.top.length ? row.push('') : null;
    });
  }


addRows() {
    this.left.push('');
    this.data.push(new Array(this.top.length).fill(''));
  }

You can find a functional solution here along with added change detection:

https://stackblitz.com/edit/angular-2kgmkh?file=src/app/app.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

Creation of Date object

Trying to create a new Date object with the constructor new Date(24, 2, 1, 0, 0 ,0) is causing an issue where it defaults to using setYear instead of setFullYear, resulting in the year being set as 1924. While this may work in most cases, I need the abilit ...

Are multiple click events needed for identical buttons?

In my component, there is an HTML structure like this: <div id="catalogo" class="container"> <div class="row"> <div *ngFor="let artista of artistas" class="col-sm" style="mar ...

Switching the CSS style within a basic jQuery accordion with just a click

I created a basic accordion using jQuery. It allows the user to toggle the items open and closed, and automatically closes any other active items. Check out the code snippet below: $(document).ready(function($) { $('#accordion').find(&apo ...

Angular 2 web SQL definitions

Currently, I am developing an electron app with Angular 4 and need to integrate a database. My preference is to utilize websql, but I am facing challenges importing the necessary typings. Upon adding @types/websql to my project and writing the code: cons ...

Tab buttons that switch between different sections with just a click

Forgive me if this seems like a simple coding issue, but I struggle with javascript and need some guidance... I have a setup where two buttons (blue and yellow) toggle between different content divs. On another part of the page, there are also two buttons ...

Tips for parsing CSV files using d3 version 4

I'm currently grappling with the documentation for CSV Parse in D3. My code snippet looks like this: d3.parse("data.csv",function(data){ salesData = data; }); Unfortunately, I keep encountering this error: Uncaught TypeError: d3.parse is n ...

What is the method to incorporate @angular/fire into an Nx Workspace for an Angular project?

Incorporating @angular/fire into my Nx workspace for my Angular application is my current goal. Despite my efforts to adhere to best practices, I have not found any guidance in the official documentation on how to incorporate this library into the wor ...

Splitting large components into smaller components

I am currently in the process of splitting the code from index.tsx into two separate files: firstTab.tsx and secondTab.tsx. As of now, I have only separated the code related to the first tab into firstTab.tsx, which can be viewed in the code editor. The co ...

Difficulty in HttpRequest handling between Angular and .Net

My http response seems to be causing some trouble, and I'm completely stumped on what the issue might be. Can someone provide assistance, please? import { Component, OnInit } from '@angular/core'; import {SharedService} from 'src/app/sh ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

Dynamic Variable Typing in TypeScript: Adjusting variable types on the fly

I am working with 2 variables named locals and visitants. These variables can either be of type PlayerDto or TeamDto, which will be determined by a third variable called competitor_type. If competitor_type is player, then I need to assign a list of Players ...

What is the best way to initiate a local Node.js server specifically when launching a desktop Electron application?

I am looking to ensure that my node js server runs while my electron app is open. One method I have attempted is using the child_process module to execute a shell command as shown below: const {exec} = require('child_process') const startDBServ ...

Retrieve the desired destination URL in the CanActivate guard when lazily loading modules in Angular

I am facing an issue with retrieving the target URL in the canActivate guard. Even though I have set up preloadingStrategy: PreloadAllModules in RouterModule.forRoot, the url property of ActivatedRoute does not contain the path. Here are the contents of bo ...

Defining preset values within a TypeScript model class

Suppose I have a User class and I want to instantiate only predefined 'status'. Is this the optimal approach? Are there any other alternatives? What is the correct way to achieve this? Thank you in advance. export class User { constructor( ...

Angular-ui typeahead feature allows users to search through a predefined

I recently developed a typeahead feature using the angular-ui library. Here is the current HTML for my typeahead: <input name="customers" id="customers" type="text" placeholder="enter a customer" ng-model="selectedCustomer" uib-typeahead="customer.fir ...

Set the datepicker with the window positioned to the right side

In my current project, I am utilizing Angular 13, Bootstrap 5, and ngx-bootstrap-fix-datepicker version 5. "bootstrap": "^5.1.3", "ngx-bootstrap": "^8.0.0", "ngx-bootstrap-fix-datepicker": "^5.6.8" ...

What is the best way to globally trigger a ModelChange event in Angular using jQuery? Alternatively, how can we use jQuery to alert Angular of any changes

My goal is to replace all date and time inputs on a page with a jQuery date time picker. I decided to use jQuery in order to avoid asking developers to change their code and replace existing components. Instead, the jQuery code will replace the date and t ...

What is the best way to add an Angular 2 component to a D3 selection?

I have implemented a chart using Angular2 and d3js with a tooltip that appears when hovering over the chart. Currently, I am directly appending a "div" element to the body and dynamically generating the innerHTML when the mouse moves within the d3.select(" ...

Combine the outcomes of various AJAX requests into one variable

Looking to make 2 recursive API calls to create a JQuery datatables page with data from the range of 2016-2021. The API responses are split based on year filters to bypass the 5000 item list limit set by Sharepoint Online. Struggling to combine all API re ...

What is the best way to make a specific update to a single dependency in package-lock.json without causing any unintended consequences?

I want to update a specific NPM (v5) dependency in my application from version 1.0.0 to 1.0.1 without altering my package.json file. "dependencies": { "package": "~1.0.0" }, Currently, my package-lock.json file lists the dependency as version 1.0.0, so ...