Encountering an issue while setting up a dynamic form using Angular 17

I am in the process of developing a dynamic form that consists of an array of payments. Users will have the ability to add new payments, delete existing ones from the array, and make edits.

Here is a snippet of the HTML code I am using:

<form [formGroup]="createLoanPaymentsForm" (ngSubmit)="createLoan()">
    <ng-container formArrayName="createLoanPaymentsForm">
        @for (
            createLoanPaymentForm of createLoanPaymentsForm.controls; // encountering an error here
            track $index
        ) {
            <div [formGroup]="createLoanPaymentForm">
                <mat-form-field appearance="fill">
                    <input matInput formControlName="title" placeholder="Lesson title" />
                </mat-form-field>
            </div>
        }
        <button mat-mini-fab (click)="addPayment()">Add</button>
    </ng-container>
</form>

Below is the configuration details of my component:

@Component({
    selector: 'app-create-loan-dialog',
    standalone: true,
    imports: [
        MatInputModule,
        MatButtonModule,
        MatDialogTitle,
        MatDialogContent,
        MatDialogActions,
        MatDialogClose,
        ReactiveFormsModule,
        MatStepperModule,
    ],
    providers: [
        {
            provide: STEPPER_GLOBAL_OPTIONS,
            useValue: { showError: true },
        },
    ],
    templateUrl: './create-loan-dialog.component.html',
})

This is how I have set up my FormGroup:

createLoanPaymentsForm: FormGroup = this.formBuilder.group({
    payments: this.formBuilder.array([]),
});

While implementing the loop, I encountered an error message which states:

Type '{ [key: string]: AbstractControl<any, any>; }' must have a 'Symbol.iterator' method that returns an iterator.

I am actively seeking a solution to resolve this bug, especially for properly looping through a FormArray in Angular 17.

Answer №1

Your HTML structure for the Reactive Form is incorrect:

  1. The formArrayName should be specified as "payments":

    formArrayName="payments"
    .

  2. You need to iterate over payments.controls in the @for loop.

  3. Within the @for loop, create each instance of FormGroup using

    [formGroupName]="index"
    .

<form [formGroup]="createLoanPaymentsForm" (ngSubmit)="createLoan()">
  <ng-container formArrayName="payments">
    @for (payment of payments.controls; track payment; let index = $index) {
      <div [formGroupName]="index">

       ...

      </div>
    }
    <button mat-mini-fab (click)="addPayment()">Add</button>
  </ng-container>
</form>
get payments() {
  return this.createLoanPaymentsForm.controls['payments'] as FormArray;
}

Check out the Demo on StackBlitz

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

Unable to locate the module 'foo' or its associated type declarations on the specified "file:..." dependency

Encountering an issue with a local file dependency: Here is the structure: /foo package.json /bar package.json In the /bar package's package.json, I have referenced the /foo package as a dependency like this: "dependencies": { " ...

How to Change the Checked State of a Checkbox in React Material UI

I am faced with a situation where I have multiple checkboxes that are used to toggle table columns on and off. The code snippet demonstrates how it looks: const [fields, setFields] = useState<Set<string>>(new Set(["name"])); const ...

What is the best way to trigger a function in the parent component when a child component is clicked

I'm facing a scenario where I have two components - a parent and a child. Within the child component, there is a button. My goal is to trigger a method in the parent component when the user clicks on that button within the child component. Any ideas o ...

Angular 8 is throwing an error stating that the property 'token' is not recognized on the 'Object' data type

As a newcomer to Angular, I have been following the MEAN Stack - Mean Auth App Tutorial in Angular 2. However, since I am using Angular 8, some of the code is deprecated due to recent updates. I have encountered an issue with the code bel ...

Creating a TypeScript definition file to allow instantiation of a module

I'm encountering an issue with creating a declaration file for an existing module. When using JavaScript, the module is imported using the following syntax: var Library = require('thirdpartylibs'); var libInstance = new Library(); I have ...

I'm curious about the location of sqlite data storage in Ionic when utilizing SqlStorage

I'm simply intrigued by the default key-value usage in this code snippet. import {Storage, SqlStorage } from 'ionic-angular'; let storage = new Storage(SqlStorage); storage.set(key, value); storage.get(key).then((value) => { ... }); Wh ...

Error in Angular service: receiving undefined value

logdetail.service.ts import { Injectable } from '@angular/core'; import { LogDetail } from './logdetail.model'; import { HttpClient } from "@angular/common/http"; @Injectable({ providedIn: 'root' }) export class LogdetailSe ...

What could be the reason for the absence of the mandatory message while using the mat datepicker

Here is a template I am currently using: <input type="text" class="form-control" name="my_date" [matDatepicker]="myDatepicker" #myDate="ngModel" [(ngModel)]="myDateValue" id="my_date" required> &l ...

Error message encountered: "Ionic 3 on IOS encountered a failure while attempting to load a webpage, indicating a problem with the server's hostname being unavailable."

Has anyone else encountered the error message from Xcode when attempting to run an Ionic 3 project on the iOS 11 simulator? Even with a new project using a blank starter template, I continue to receive the same error. https://i.sstatic.net/BXcAQ.png UPDA ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Collective picture in the exhibit

I recently created a photo gallery that showcases various images sorted by categories. In this setup, I have one object containing both images and their respective categories, and another object solely dedicated to storing the categories. The challenge I ...

Automate the selection of an item in a Primeng Listbox using Angular 2 and PrimeNg

After displaying a list using a PrimeNg Listbox (p-listbox), I needed to monitor the changes in selection by implementing the ngDoCheck lifecycle hook. Specifically, I wanted to detect when the user selected a specific group ("Group0") and then revert the ...

Hover over to reveal the button after a delay

I'm struggling with implementing a feature in my Angular code that displays a delete button when hovering over a time segment for 2 seconds. Despite trying different approaches, I can't seem to make it work. .delete-button { display: none; ...

Angular 2 rejected the request to configure the insecure header "access-control-request-headers"

My current challenge involves sending an HTTP POST request to my server. Here is the code I am using: var headers = new Headers({ 'Access-Control-Request-Headers': "Content-Type", 'Content-Type': 'application/json'}); let opt ...

The "(click)" event doesn't fire upon clicking a material icon

After creating an <a> tag with a (click) event function call, I noticed that the click event works everywhere except for the arrows mat-icons within the code snippet below: <span *ngIf="section.pages.length>0"> <mat-icon *ngIf="secti ...

Using ngFor to display images with src attribute, merging information from two different properties within the loop

One issue I am facing involves an array with properties: export interface IGameTag{ name: string; relativePath: string; filename: string; } I understand that it is possible to include the filename in the relativePath like this: <div *ngFor=" ...

Incorporate @ngx-translate into individual components within Angular 17 for enhanced translation capabilities

I have encountered an issue while using standalone components in Angular 17. Interestingly, when I used module architecture, this problem did not arise. By adding the necessary import to 'AppModule', everything worked perfectly. imports: [ Trans ...

A special term in Typescript that consistently points to the present object within the class

Is it feasible to utilize a reference to the current instance of a class in Typescript, similar to "this" in C# and Java, rather than the typical binding context interpretation in JavaScript? ...

Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books. public getBooks(): Observable<Book[]>{ ...