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

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

Exploring the distinction between "() => void" and "() => {}" in programming

Exploring TS types, I defined the following: type type1 = () => {} type type2 = () => void Then, I created variables using these types: const customType1: type1 = () => { } const customType2: type2 = () => { } The issue surfaced as "Type ...

After upgrading to Angular 15, the Router getCurrentNavigation function consistently returns null

Since upgrading to angular 15, I've encountered a problem where the this.router.getCurrentNavigation() method is returning null when trying to access a state property passed to the router. This state property was initially set using router.navigate in ...

Is it possible to utilize an ng template within one component and then reference its template in another HTML file?

I'm experimenting with using ng-template in a separate component and referencing it in other parts of the html. Is this possible? I've tried different approaches but seem to be missing something. Can you help me understand where I might be going ...

The setTimeout() function caught in an endless cycle

Is there a way to retrieve the height of divs used in multiple components? The HTML structure I am working with is as follows: <div #dataHeadlines *ngFor="let group of catt" [ngClass]='hf(dataHeadlines)'> <h4>{{ group }}< ...

Facebook is failing to detect meta tags for Angular Universal

I am facing an issue where the meta tags are not showing up on my article pages for Facebook sharing, despite using Angular Universal with Server-side rendering. Although Google Indexing is working fine and the meta tags are visible in the page source, the ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

Revolutionizing the way data is updated: Angular 2 and Node JS collaborate

In my Angular 2 application, I have incorporated a dynamic navbar that displays the count of unread messages for each user. Interestingly, when a person clicks on a specific message, it is correctly marked as read in the database. However, an issue arises ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Angular2's integration of backend API calls

My backend calls are functioning correctly, but I'm encountering an issue with promises. I am unable to retrieve the data from the first promise in order to make the second call. Any insights on where I might be going wrong? login() { if (thi ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

Angular validation with input binding using if statement

I have developed a reusable component for input fields where I included a Boolean variable called "IsValid" in my typescript file to handle validation messages. Here is the code from my typescript file: export class InputControlsComponent implements OnIn ...

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

Querying with Node SQLite fails to return a value

So, here's my little dilemma: I have 3 methods that need to access a database file (SQLite3). export function F_SetupDatabase(_logger: any): void export function Q_RunQuery(query: string, db: "session" | "global"): any export func ...

Troubleshooting compilation problems in Angular2 with nested components

I have created two components in Angular2 using TypeScript: app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles : [` .parent { background : #c7c7c7; ...

When running `npm install` and `ionic build`, not all node modules are installed

Currently facing some issues with node_modules while trying to build an existing Ionic app. Here is the package.json file: { "name": "My App", "private": true, "scripts": { "clean": "ionic-app-scripts clean", "build": "ionic-app-scripts buil ...

What is the best way to integrate Angular types (excluding JS) into tsconfig to avoid the need for importing them constantly?

Lately, I've been dedicated to finding a solution for incorporating Angular types directly into my .d.ts files without the need to import them elsewhere. Initially, I attempted to install @types/angular, only to realize it was meant for AngularJS, whi ...