Nested formArrays within formArrays in Angular 4

I've been working on implementing a FormArray inside another FormArray, but it doesn't seem to be functioning correctly. I also tried the solution provided in the link below, but it didn't work for me.

How to get FormArrayName when the FormArray is nested in another FormArray?

Could someone please assist me in identifying what I might be doing wrong in the code snippet below?

HTML

<div [formGroup]="MainFormGroup" class="custom-auto-complete">
  <mat-radio-group matInput formControlName="Applies">
    <mat-radio-button *ngFor="let applie of applies" [value]="applie.id">{{applie.value}}</mat-radio-button>
  </mat-radio-group>           
  <div formArrayName="FormArrayOne">
    <div *ngFor="let mains of MainFormGroup.get('FormArrayOne')['controls']; let i=index">
      <div [formGroupName]="i">
        <mat-icon *ngIf="MainFormGroup.get('FormArrayOne').length > 1" (click)="removeMarket(i)">remove_circle</mat-icon>
        <mat-icon (click)="addOne()"> add_circle</mat-icon>
        <mat-form-field>
          <input matInput formControlName="OneField" value="">
        </mat-form-field>
        <div formArrayName="FormArrayTwo">
          <div *ngFor="let Market of MainFormGroup.get('FormArrayTwo')['controls']; let j=index" >
            <div [formGroupName]="j">            
              <mat-form-field class="formfieldsControl">
                <input matInput formControlName="Destination">
              </mat-form-field>
            </div>
          </div>
        </div>         
      </div>
    </div>
  </div>    
</div>

TS

public ngOnInit() {
  this.MaintFormGroup = this._fb.group({
    Applies : '',
    FormArrayOne: this._fb.array([
      this.initArrayOne(),
    ])
  });
}
public initArrayOne() {
  return this._fb.group({
    OneField: '',
    FormArrayTwo : this._fb.array([
      this.initFormArrayTwo()
    ])
  });
}
public addMarket() {
  const control = <FormArray> this.MaintFormGroup.get('FormArrayOne');
  control.push(this.initArrayOne());
}
public removeMarket(i: number) {
  const control = <FormArray> this.MaintFormGroup.get('FormArrayOne');
  control.removeAt(i);
}
public initFormArrayTwo() {
  return this._fb.group({
    Destination : ''
  });
}
public addFormArrayTwo() {
  const Control = <FormArray> this.MaintFormGroup.get('FormArrayTwo');
  Control.push(this.initFormArrayTwo());
}
public removeFormArrayTwo(j: number) {
  const Control = <FormArray> this.MaintFormGroup.get('FormArrayTwo');
  Control.removeAt(j);
}

Answer №1

Check out this link for a simplified solution to the issue. Feel free to explore my project on codepen showcasing deep nested forms.

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

What is preventing me from loading a module using a variable containing a string?

This code snippet demonstrates how the module can be successfully loaded using import('test'), but not with the second example. These lines of code are executed within an Angular 9 application utilizing the default Webpack configuration. var tes ...

An error was encountered in the rxjs-compat module at operator/shareReplay.d.ts line 2, character 10: TypeScript error TS2305

Currently, I am in the process of upgrading a basic Angular skeleton application from version 5 to version 6. However, I have encountered an issue while attempting to run the application: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): ...

Error: Attempting to access 'config' property of undefined variable

I am currently utilizing Vue 3 with Typescript and primevue. After integrating primevue into my application, I encountered the following errors and warnings. The issue arises when I attempt to utilize the primevue 'Menubar' component, however, wh ...

How to extract a specific Observable<T> from an Observable<T[]> array in RxJS

When studying Angular, I created a simulated web service that accomplishes two tasks: It provides an Observable of an array (Observable<T[]>) It offers an item identified by ID as an Observable (Observable<T>) This is the approach I used: e ...

Struggling to successfully map angular model data to a Spring POJO class

I am currently having issues mapping an Angular model class to my Spring model class. When I try to do so, all the entities in the Spring model class show up as null. I have included the code snippets below that I used for mapping, but unfortunately, it fa ...

Execute the render function of the components that have been passed as

I've been grappling with a challenge lately - figuring out how to invoke a passed component's render function within another function. Let's say I have two functions named A and B: export const A = (value: any) => { return ( <div& ...

Exploring the possibilities of developing WebComponents within Angular using TypeScript

My Angular application was originally created using the default method with ng new project-name". However, for performance reasons, I had to incorporate single standard WebComponents. The JavaScript code associated with these components is stored in a ...

Discovering ways to optimize argument type declarations in TypeScript

If we consider having code structured like this: function updateById( collection: Record<string, any>[], id: number, patch: Record<string, any> ): any[] { return collection.map(item => { if (item.id === id) { return { ...

Create a custom definition for the useSelector function within a separate TypeScript file in a React

Question: Is it possible to define a type like <TRootState, string> in an external file and use it directly inside multiple Component files? External file: export type TUser = <TRootState, string> // This method does not work Component's ...

Encountering a 500 error (Internal Server Error) while trying to connect API Laravel 5.4 with Angular 2

Every time I try to submit a form from an Angular form to my API built on Laravel, I encounter a 500 error (Internal Server Error) in the console. What could be causing this issue? Note: The backend API functions perfectly when tested with POSTMAN. This ...

Error encountered when attempting to inject a service into another service due to circular dependency issues

I have encountered an issue while working on my Angular 5 application where I am facing errors when trying to inject one service into another service. Below is a snippet of the DataService: import { Injectable } from '@angular/core'; import { H ...

What is the best way to spy on child components within an Angular application?

The Angular tutorials feature an example of a HeroesComponent with a child component named HeroesListComponent. Within the HeroesListComponent, there is a usage of the HeroesService to execute the getHeroes() function. In order to utilize the spyOn funct ...

The ng-bootstrap package is not fully compatible with Bootstrap 4 Alpha 6, particularly when it comes to collapsible elements such as forms

Just a heads up for everyone, the current version of ng-bootstrap is not compatible with the latest release of Bootstrap (Alpha 6). This includes collapsing elements like collapses, dropdowns, navs, etc. I haven't figured out how to make the package ...

What is the best way to align a title above menu items within a Material UI app bar when using TypeScript and React?

Check out my current app bar design: app bar image Here is the inspiration for the app bar layout I'm aiming for (title above menu items): inspiration app bar goal This snippet showcases my code: import * as React from 'react'; // More cod ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

Dealing with React and Firebase Authentication Errors: How to Handle Errors for Existing Accounts with Different Credentials

According to the documentation at https://firebase.google.com/docs/auth/web/google-signin#expandable-1, when error.code === 'auth/account-exists-with-different-credential', signInWithPopup() should return an error.email. However, in my specific c ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

Firefox unable to detect click events

I am facing an issue with my Angular 2 website where it is not functioning correctly in Firefox. The main problem lies in the fact that Firefox does not recognize the event being passed into my TypeScript function. This event specifically pertains to a mou ...

Populating a data grid with several objects within a JSON object

I am currently developing a project utilizing React with typescript and materialUi. My task is to retrieve data from a JSON fetch request and display it in a DataGrid. The structure of the JSON data is as follows: { id: "1234567890", number: ...

Ways to sort mat-select in alphabetical order with conditional names in options

I am looking to alphabetically order a mat-select element in my Angular project. <mat-select [(ngModel)]="item" name="item" (selectionChange)="changeIdentificationOptions($event)"> <mat-option *ngFor="let item of items" [value]="item"> ...