Encountering an error when initializing a form array with an existing array of multiple objects in Angular 13: "Control not found with

Hey there, I'm brand new to Angular and I'm trying to set up a form array with an existing array that contains multiple objects. However, I keep encountering the following error:

Cannot find control with path: 'variable-> 0 -> id'

Here is the HTML code I have:

<form [formGroup]="myForm">
  <div formArrayName="box">
    <div *ngFor="let b of getForm(); let i = index">
      <fieldset [formGroupName]="i">
        <legend> <h3>FRUIT DETAILS {{ i + 1 }}:</h3>  </legend>
        <label>Fruit Name: </label>
        <input [formControlName]="name" />
        <label>Fruit Value: </label>
        <input [formControlName]="value" />
      </fieldset>
    </div>
  </div>
  <br />
</form>

<pre>{{ myForm.value | json }}</pre>

And this is the TypeScript code accompanying it:

myForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.myForm = this.fb.group({
    box: this.fb.array([]),
  });

  let fruits = {
    data: [{name: 'Apple', value: 10}, {name: 'Orange', value: 5},{name: 'Banana', value: 20}]
  };

  for (let f of fruits.data) {
    const control = <FormArray>this.myForm.get('box');
    control.push(this.fb.group({name: f.name, value: f.value}));

    console.log(f);

  }

  this.myForm.patchValue({ box: fruits.data });
  //console.log(this.myForm.value);
}

getForm(): any {
  return this.myForm.get('box')['controls'];
}

Answer №1

I made two key adjustments to ensure functionality:

First, in the TypeScript file, I revamped the getForm() method as the original code was no longer working in my new Angular 15 project. To avoid potential issues down the line, I updated it as follows:

getForm(): any {
    const form = this.myForm.get('box') as FormArray;
    return form['controls'];
}

Secondly, in the HTML file, I eliminated the brackets around formControlName. This adjustment ensures that name and value are recognized as strings rather than variables:

<form [formGroup]="myForm">
    <div formArrayName="box">
      <div *ngFor="let b of getForm(); let i = index">
        <fieldset [formGroupName]="i">
          <legend> <h3>FRUIT DETAILS {{ i + 1 }}:</h3>  </legend>
            <label>Fruit Name: </label>
            <input formControlName="name" />
            <label>Fruit Value: </label>
            <input formControlName="value" />
        </fieldset>
      </div>
    </div>
   <br />
</form>

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 type definition file for 'zen-observable'

While working with Ionic 3, I decided to use the AWS default template and encountered an error: > ionic start app0 aws // aws is a default starting app in Ionic3 > cd app0 > ionic serve However, when I tried to serve the application, I received ...

Having trouble getting Angular's ngClass directive to work correctly when applying multiple conditions

Struggling to make multiple conditions work with [ngClass] Check out a.component.html <div class="version-content" *ngFor="let version of versions; let lastVersion = last" [ngClass]="(version.isComingSoon === true) ? 'dashed': 'solid"> ...

"Implementing a retry feature for Angular http requests triggered by a button

Imagine having a situation where a component has a method that triggers an http request defined in a service. The observable is subscribed to within the component: Component: fetchData() { this.apiService.fetchDataFromServer().subscribe( respo ...

What is the best way to transform all elements on a webpage into a dynamic scrolling marquee?

Is there a way to make every div in a web application scroll like a marquee? Perhaps by using a specific CSS class or other method? The application is built with Angular 4 and Bootstrap. ...

The attribute 'attribs' is not found on the 'Element' type in cheerio

When I run my code, I encounter an error that says Property 'attribs' does not exist on type 'Element'. It's puzzling to me why this error is being thrown. After examining the type definitions of cheerio, I discovered that attribs ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError error during Karma testing

Testing out some functionality in one of my components has led me to face an issue. I have set up an observable that is connected to the paramMap of the ActivatedRoute to retrieve a guid from the URL. This data is then processed using switchMap and assigne ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

Updates made to Angular components do not get transpiled to JavaScript

Embarking on my first ASP.NET Core application journey with Angular 2! User access is a top priority for the application. Facing the absence of an Angular template in Visual Studio 2017, I opted to use Powershell and Yoman to generate an Angular project s ...

Running into issues compiling Ionic 4 with Angular 7 inside a Docker container

Facing Issues Compiling Ionic 4 with Angular 7 in Docker I am trying to compile a project using Ionic 4 and Angular 7 within Docker. Here are the steps I have taken: I manually created an image with Java JDK version 8, following this article How To Ins ...

Tips for managing Razorpay responses in Angular 2

I'm currently in the process of finalizing my payment transaction through RazorPay Payment gateway, and I've attempted to do so as shown below: var options = { "key": "XXX", "amount": 100, "name": "Ezshipp", "description": this.it ...

Go through each item in the array and change its properties

When retrieving data from the database, I receive the following information: "Data": [{ "mainData": [{ "_id": ObjectId("5ab63b22d012ea2bc0bb7e9b"), "date": "2018-03-24" }], "files": [ { "_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"), ...

Generics-based conditional type that verifies entry properties

I developed a function that accepts an argument with two different architectures. I intentionally avoided enforcing rules to allow flexibility for the user, which is now causing me some headaches ...

The CSS3D object stands out among 3D objects, maintaining its visibility even as the scene is rotated

I'm utilizing the CSS3DRenderer to render HTML on FBX 3D objects. Everything seems to be working well, except that when I rotate my scene, the HTML becomes visible through the 3D objects as if they were transparent. I am relatively new to Three.js and ...

Exploring Ionic 2: Utilizing Service and modalCtrl for enhanced functionality

I am relatively new to using Ionic 2. Recently, I created a service that contains all my filters (ModalCtrl) with custom search input and checkboxes. I am passing parameters between them but I am unsure of how to keep the service active and waiting for the ...

Dealing with challenges in integrating ngx-masonry with Angular 14

I am currently working with Angular 14 framework and the ngx-masonry library (https://www.npmjs.com/package/ngx-masonry/v/14.0.1). However, I am facing some issues where it is not functioning correctly. I would appreciate any assistance or guidance on how ...

Is there a way for me to program the back button to navigate to the previous step?

I am currently developing a quiz application using a JSON file. How can I implement functionality for the back button to return to the previous step or selection made by the user? const navigateBack = () => { let index = 1; axios.get('http ...

Numerous mistakes detected in the TypeScript code

I've implemented the following class within an ASP.NET Core React application: import * as React from 'react'; interface MyInputProps { inputType: string; id: string; className: string; parentFunctio ...

The router's handler function sends back a collection of objects, but for some reason, the client is not receiving them in JSON format even though the response

I am currently developing an Express.js project using Typescript. In my project, I have defined an enum and an interface as follows: export enum ProductCategory { ELECTRONICS = 'electronics', CLOTHING = 'clothing', TOYS = & ...

Retrieve an object containing properties specified in the function's parameter list

I am currently working on developing a function that can dynamically create and return an object with properties based on an array of strings provided as parameters. type Foods = 'apple' | 'banana' | 'pear'; function foodObje ...

An issue occurred: the channel has been terminated within the ChildProcess.target.send function at internal/child_process.js, line 562, character

My Angular 5 application is giving me an error message that says "ERROR in Error: channel closed". This occurs after running the application. The issue seems to persist even though it works fine for a few minutes after executing ng serve. Has anyone else e ...