The error message from ANGULAR states that it cannot locate the control with the specified path: 'childrenFormArray -> [object Object] -> gender'

I'm currently working on an angular project and facing a challenge in adding multiple children with their age and gender dynamically using reactive forms. Although I can add the form, I am having trouble with the delete functionality as it keeps throwing an error message:

Cannot find control with name: 'childrenFormArray'

Here is my TypeScript code:

 ngOnInit(): void {
   this.childrenFormGroup= this.formBuilder.group({
     childrenFormArray: this.formBuilder.array([ this.createItem() ])
   });
 }

 createItem(): FormGroup {
   return this.formBuilder.group({
     gender: new FormControl(''),
     age:  new FormControl(''),
  
   });
 }

 addItem(): void {

   if(this.childrenFormGroup.get('childrenFormArray'['controls'].length<this.numberOfChildren) {
       this.childrenFormArray = this.childrenFormGroup.get('childrenFormArray') as FormArray;
       this.childrenFormArray.push(this.createItem()); 
       this.addItem();
   }
   else if(this.childrenFormGroup.get('childrenFormArray'['controls']>this.numberOfChildren) {
     this.childrenFormArray = this.childrenFormGroup.get('childrenFormArray') as FormArray;
     this.childrenFormArray.removeAt(this.childrenFormArray.length-1);
     this.addItem()
 }

}

This is my HTML code to display the form:

  <div class="col-12 ">
     <fieldset class="form-group ">
       <label class="form-label " for="numberOfChildren">Number Of Children</label>
          <input type="number" class="form-control " id="numberOfChildren"   [ngModelOptions]="{standalone: true}" placeholder="Enter number of children" (input)="addItem()" [(ngModel)]="numberOfChildren" required>
          <div formArrayName="childrenFormArray" *ngFor="let item of childrenFormGroup.get('childrenFormArray')['controls']; let i = index;">
             <div [formGroupName]="childrenFormGroup.get('childrenFormArray')['controls'][i]">
                <select formControlName="gender" >
                   <option value="male">Male</option>
                   <option value="female">Female</option>
                   <option value="other">Others</option>
                </select>
                 <input type="number" formControlName="age" placeholder="Age of Child">
      </div>

Answer №1

Make sure that the structure of your form matches your HTML, for example:

  childrenFormGroup: FormGroup
    childrenFormArray : FormArray
      [0] : FormGroup
          gender: FormControl
          age: FormControl
      [1] : FormGroup
          gender: FormControl
          age: FormControl

Now you can adjust your form to align with the above structure:

<form [formGroup]='childrenFormGroup'>
    <div class="col-12 ">
     <fieldset class="form-group ">
       <label class="form-label " for="numberOfChildren">Number Of Children</label>
          <input type="number" class="form-control " id="numberOfChildren"   [ngModelOptions]="{standalone: true}" placeholder="Enter number of children" (input)="addItem()" [(ngModel)]="numberOfChildren" required>
          <ng-container formArrayName="childrenFormArray">
            <div *ngFor="let item of childrenFormGroup.get('childrenFormArray')['controls']; let i = index;" [formGroupName]='i'>
             <div>
                <select formControlName="gender" >
                   <option value="male">Male</option>
                   <option value="female">Female</option>
                   <option value="other">Others</option>
                </select>
                 <input type="number" formControlName="age" placeholder="Age of Child">
      </div>

Pay attention to these two lines in particular:

<ng-container formArrayName="childrenFormArray">
...
 [formGroupName]='i'

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

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

What is the definition of a non-arrow React functional component in TypeScript?

Defining types for a React functional component in TypeScript can be done like this: export const Component: React.FC = () => { return // Content }; But how would you define the types for a non-arrow function? function Component() { return // Con ...

Guide on accessing intellisense for mapGetters, mapActions in Vuex using TypeScript without the need for class-style or decorators syntax

I have been using Vue.js and Vuex for a while now, but always with JavaScript. Recently, I decided to try using Vue with TypeScript, specifically with nuxt.js, but without utilizing decorators or style-class-components. I want to stick to the normal Vue s ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

What steps should we take to ensure that the container beside the fixed left navigation bar is responsive?

Currently, I am working on creating a user interface that features a fixed navigation bar on the left hand side and a responsive content window. Here is what I have implemented so far: <div style="width: 15%; float: left; display: inline;"> <na ...

The Ionic and Angular application solely displays dynamic HTML with no encapsulation using ViewEncapsulation.None

I'm struggling to grasp the concept of encapsulation: ViewEncapsulation.None within the @Component. @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], encapsulation: ...

What is the best way to connect a ref to a stateless component in React?

I need help creating a stateless component with an input element that can be validated by the parent component. In my code snippet below, I'm facing an issue where the input ref is not being assigned to the parent's private _emailAddress propert ...

"Design a function that generates a return type based on the input array

Created a function similar to this one // window.location.search = "?id1=123&id2=ABC&id3=456" const { id1, id2, id3 } = readArgsFromURL("id1", {name: "id2", required: false}, {name: "id3", required: true}) ...

Building a personalized radio button Angular component for optimal integration with ReactiveForms

I have developed a custom radio button that stores the current value in the model attribute and checks if the model and value are equal in terms of styling. Everything functions smoothly when using template forms with the [(ngModel)] attribute on the tag. ...

External function does not support jQuery types

In my theme.js file, I currently have the following code: jQuery(function ($) { accordion($) }) const accordion = ($) => ... By placing the accordion function directly into the jQuery function, Typescript is able to assist with the installed jquery ...

Finding a date from a calendar with a readonly property in Playwright

Just starting out with the playwright framework after working with Protractor before. I'm trying to figure out the correct method for selecting a date in Playwright. selector.selectDate(date) //having trouble with this ...

What is causing pre-defined variables to act unexpectedly in Cypress?

Encountering unexpected results while pre-defining element variables and using them later in Cypress 10 with Cucumber. Let's take a look at this login test: Given("I'm logged in as Default user", () => { cy.visit('/ ...

Display JSON data in Angular view by extracting the desired value

Hey there! I have a GET response data with a field like "DeletionDate": "0001-01-01T00:00:00". What I'm trying to achieve is to remove the time part T00:00:00 and only display half of the value in my views. Is there a way to trim the value and show it ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

It appears that Typescript mistakenly interprets a class or type as a value, indicating that "'Classname' is being referred to as a value but used as a type here."

I want to pass an Object of a React.Component as "this" to a Child React.Component in the following way: component 1 file: class Comp1 extends React.Component<...,...> { ... render() { return (<Comp2 comp1={this}/> ...

What is the best way to assign an index signature to a plain object?

Currently, I have this object: const events = { i: 'insert', u: 'update', d: 'delete' }; I am struggling to assign an index signature to the object. When I try the following: export interface EventsSignature { [key: ...

Inversify is a proven method for effectively injecting dependencies into a multitude of domain classes

Struggling to navigate dependencies and injections in a TypeScript-built rest web service without relying heavily on inversify for my domain classes, in line with the dependency inversion principle. Here's an overview of the project structure: core/ ...

Enroll in a stream of data while iterating through a loop in an Angular application

I encounter a situation where I must subscribe to an Observable, iterate through the response, and then subscribe to another Observable using data from the initial Observable. getTasks(taskType: Observable<any>): void { taskType // Subscribing ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

Angular application using ngrx-store-localstorage does not retain data after a page refresh

Looking to incorporate ngrx into my authentication flow with the help of ngrx-store-localstorage for token persistence between browser sessions. After logging in, I can see the token value stored like this: {"token":{"token":"e5cb6515-149c-44df-88d1-4ff1 ...