Nested Angular formArrays within formArrays

Currently working on inline editing in my project, I am attempting to patch value data from the server. Within my formArray for the accountNumbers array, I am encountering an issue when trying to change the value of inputs. The error message reads: Error: Cannot find control with path: 'type -> options -> 0 -> accountNumbers -> accountNumber'. What might be causing this problem? For reference, here is my stackblitz

.ts

    this.editCompanies = this._formBuilder.group({
      type: this._formBuilder.group({
        options: this._formBuilder.array([]),
      }),
    });

    const control = <FormArray>this.editCompanies.get('type.options');
    this.items.forEach((x) => {
      control.push(
        this.patchValues(x.name, x.identificationCode, x.accountNumbers)
      );
      console.log(control);
    });
  }

  patchValues(name, identificationCode, accountNumbers) {
    return this._formBuilder.group({
      name: [name],
      identificationCode: [identificationCode],
      accountNumbers: new FormArray([this.initOptions()]),
    });
  }

  initOptions() {
    return new FormGroup({
      accountNumber: new FormControl(''),
    });
  }

.html

  <div class="col-lg-5 accountNumbers">
    <span formArrayName="accountNumbers">
        <span class="value" [ngClass]="{'my_class': hidemeSub[index] === true}"
        [hidden]="hidemeSub[index]"> {{item.accountNumbers}}</span>
        <input type="text" class="form-control" formControlName="accountNumber" [hidden]="!hidemeSub[index]">
    </span>
  </div>

Answer №1

If you take a closer look at the path, you will notice that the index of the element in the second FormArray is missing.

type -> options -> 0 -> accountNumbers -> [missing_index] -> accountNumber

Just like how you assign the first index of FormArray using:

<div class="example-accordion-item-header nusx row" formArrayName="options"
    *ngFor="let item of items; let index = index;">
    <ng-container [formGroupName]="index">

You also need to iterate through the items in the second array and assign the second index using the appropriate ControlName directive. Since it is also an array of FormGroup, you can do something like this:

<ng-container 
  *ngFor="let accountNumber of item.accountNumbers; let accIndex = index" 
  [formGroupName]="accIndex"
>
  <input type="text" class="form-control" formControlName="accountNumber" [hidden]="!hidemeSub[index]">
</ng-container>

EDIT

It's important to properly initialize the FormGroup for the account numbers by creating one group per account:

patchValues(name, identificationCode, accountNumbers) {
  return this._formBuilder.group({
    ...
    accountNumbers: new FormArray(
      accountNumbers.map((account) => this.createAccountControl(account))
    ),
  });
}

//I changed the method name to createAccountControl to better reflect its purpose
createAccountControl(initialValue: string = '') {
  return new FormGroup({
    accountNumber: new FormControl(initialValue),
  });
}

Cheers

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

Issue with Angular Filters: Difficulty Arises When Search Box is Cleared

I have a list of objects that I am displaying, and I added a search box to filter a column. When I enter a value, the data is filtered correctly. However, when I clear the search box, I do not get all the data back; I remain stuck with the initially search ...

Encountering parameter issues while working with Google Maps React in TypeScript

Currently, I'm utilizing TypeScript in this particular file. import React, {Component} from 'react' import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react'; import { coordina ...

The issue of Angular, ng-ckeditor, and the problematic editor-destroy-iframe bug

This particular post pertains to [email protected] and is filled with information on [email protected]. Despite finding similar questions on SO, I am convinced that this remains an unresolved issue. Please refrain from marking this post as a dup ...

Excluding node modules from Webpack TerserPlugin

I am currently working on a custom Angular Builder and I need to exclude an entire module from the minification/optimization process. According to the Webpack .md file: exclude Type: String|RegExp|Array Default: undefined This setting is used to spe ...

The req.body parameter is consistently devoid of any content after being submitted

I recently switched to using a Typescript Fetch wrapper for my post and get requests, but I am facing an issue where I am getting an empty object on post requests (get requests work fine). This was not a problem when I was using Vanilla Js. My Nodejs code ...

Angular Material Password Confirmation

Currently, I am working on implementing user authentication using Angular Material. Specifically, I am focusing on displaying the appropriate error message when the confirmed password does not match the initially entered password. Below is the snippet of ...

The error thrown is: "Attempting to access the 'authService' property of an undefined object using TypeDi."

In the process of setting up an authentication system, I have created a class called AuthRouter: import { Router } from 'express' import Container, { Service } from 'typedi' import AuthenticationController from './index' @Ser ...

The function parameter in Angular's ngModelChange behaves differently than $event

How can I pass a different parameter to the $event in the function? <div class='col-sm'> <label class="col-3 col-form-label">Origen</label> <div class="col-4"> <select ...

Tips and Tricks for Resizing Images within an Angular iframe

Can anyone help me figure out how to make the image content inside my iframe fit perfectly within the frame? I noticed that when displaying a PDF it scales correctly, but when displaying a PNG image it does not scale properly and looks distorted. Any ass ...

Retrieve the component when there is a change in the variable in Angular versions greater than 4

When invoking the ngx-ebar-treemo component in my main component, I use the following syntax: <ngx-ebar-treemo *ngIf="type=='Bar' && graphic" type1="{{type1}}" type2="{{type2}}"></ngx-ebar-treemo> I need to call this compone ...

Accessing a variable from different tabs in an Ionic 3 weather application

I am currently exploring the world of app development and have decided to create a weather application. The main goal of this app is to display the current weather using data from the openweathermap.org API. To achieve this, I have divided my app into 3 ta ...

Retrieve the ultimate information from the Angular service

Within my angular 6 project, I am dealing with a product_id array, product_id: any = ["123", "456"]; ngOnInit : ngOnInit() { this.product_id.forEach(element => { this.httpClient.get('https://api.myjson.com/bins/hiolc').subscribe ...

Encountering an issue connecting to the backend server for the

I am attempting to make a POST request from my Angular 2 frontend to my Spring backend, but I am encountering an error. The error message: GET http://localhost:8080/loginPost 405 () Failed to load http://localhost:8080/loginPost: No 'Access-Control ...

Error in CORS header due to absence of 'audience' token in Ionic 4 - Lambda configuration

I have an app built with Ionic framework running on my computer (localhost) that is accessing routes from my Lambda application. However, when I attempt to access a route, I encounter the following error: Cross-Origin Request Blocked: The Same Origin Po ...

Having trouble retrieving data from a behavior subject while using switchMap and refreshing in RxJS

app.component.ts import { Component, OnInit } from '@angular/core'; import { of } from 'rxjs'; import { TestService } from './test.service'; @Component({ selector: 'app-root', templateUrl: './app.component. ...

Is Intellisense within HTML not available in SvelteKit when using TypeScript?

Having trouble with intellisense inside HTML for a simple page component. Also, renaming properties breaks the code instead of updating references. Typescript version: 4.8.4 Below is the code snippet: <script lang="ts"> import type { Bl ...

Having trouble compiling an Ionic/Cordova app for Android?

I have encountered an issue while trying to build my Ionic/Cordova app for Android. It runs smoothly on iOS, but when attempting to build for Android, I keep receiving an error message. The specific error is: Error: Attribute meta-data#android.support.V ...

What are some ways to enhance the content within a JWT?

After following this tutorial, I am interested in adding additional information to the token. Specifically, I would like to include an 'accessRights' field that can be used for user authorization in both the backend and Angular. Where should I i ...

I am unable to run ng serve at the moment

Every time I enter ng serve it shows: Your global Angular CLI version (10.0.1) is higher than your local version (6.2.9). The local Angular CLI version will be used. To prevent this warning, use ng config -g cli.warnings.versionMismatch false. Schema va ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...