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

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

Angular 2 observables not functioning properly with web API

I have been encountering issues while trying to access the WEB API using the http.get method. The service I am implementing utilizes observables, but it does not seem to be functioning properly. There are no calls being made to the server and no error me ...

encountered an issue when testing a dynamic route in Next.js with postman

I recently created a new API route named route.ts, where I included two different routes. One route retrieves all users from the database, while the other retrieves a specific user based on their ID passed as a query parameter. However, when testing these ...

Having difficulty incorporating an input value into an Angular function

For a school project, I am creating a login form using Angular. Below is the HTML code: <input type="text" ng-model="username" name="username" /> <input type="text" ng-model="password" name="password" /> <button (click)="submit(username, pa ...

Vue's v-on:click feature stops functioning correctly post-build

I have successfully integrated the Vue slide example from this link into my Angular template. Everything works fine when running ng serve, but after building with ng build and then trying to start it again with ng serve or from the dist folder using npm s ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Using a dictionary of class types as input and returning a dictionary of their corresponding instances

Is there a way to create a function that takes a dictionary with class values as an argument and returns a dictionary of their instances? For example: classes C1, C2 function f: ({ name1: C1, name2: C2 }): ({ name1: new C1() name2: new C2 ...

Executing functions before the data is loaded in an Angular application

Hey there, I'm relatively new to Angular and I've been facing some difficulties when it comes to loading data. In the code snippet below, you'll notice that I have two services being called. Each service logs something to the console. After ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Taking advantage of Input decorator to access several properties in Angular 2

I am currently working on a component that is designed to receive two inputs through its selector. However, I would like to make it flexible enough to accept any number of inputs from various components. Initially, I tried using a single @Input() decorator ...

Encountering an external babel register error when trying to initiate npm start

I initiated my angular Application using npm start with gulp and babel enabled. However, upon starting, the browser continuously loads and displays an error message stating "requiring external babel register". Below are the logs from the terminal: [19:52 ...

Is there a way for the parent class to access the child class in Angular 2?

Seeking guidance on accessing a child class from a parent class in my Angular 2 application with Typescript. The structure of the parent and child classes are as follows: The parent class, AllDataPageComponent: @Component({ selector: 'all-data-p ...

Sending information to child components within the "router-outlet"

I have a parent component that communicates with the server and receives an object: // parent component @Component({ selector : 'node-display', template : ` <router-outlet [node]="node"></router-outlet> ` }) exp ...

Circular dependency in Angular between two components

I'm currently working on an Angular 7 project that involves managing different entities, like Cars and Students. The structure of the application components can be represented by the following hierarchy: Cars Cars/CreateCar (dialog) Students Studen ...

Encountering a issue while attempting to sign up for a function within the ngOnInit lifecycle

I keep encountering the error message "Cannot read property 'name' of undefined" when working with a basic API that returns information about vehicles. The Vehicle object has several fields: public int Id {get ;set;} public int ModelId { ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

How can I display an ng-container or ng-template without using *ngIf?

I am trying to incorporate the tappable directive into the ion-card component within a custom component. I am using an @Input() myInputBool, similar to this: <ng-container *ngIf="myInputBool"> <ion-card> <ng-container r ...

Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format. Current Output let temp = [ { "imagePath": "", "imageDescription": [ { "language": "en ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...

Starting a line series from the beginning of the y-axis on a bar chart using chart.js

We have a new request from the business regarding the implementation of chart.js. Take a look at the image below, which shows a combination of bar and line charts. The line chart contains only a few data points. Within the application, users can choose a ...