Issue with FormArray within another FormArray in Angular

I've been tackling a challenging task involving a dynamic Form in Angular where an array needs to be nested within another array.

However, I've encountered an issue with my form that throws the following error:

[Cannot find control with path: 'gruppen -> 0 -> prueffolge'][1] Outlined below is the object structure I'm working with:

"pruefplanTemplate": {
  "gruppen": [
      "prueffolge": 100,
      "name": "test",
      "pruefungen": [
        "..": "",
        "..": ""
      ]
  ]
}

This is my code snippet: Component:

import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-pruefplan-template',
  templateUrl: './pruefplan-template.component.html',
  styleUrls: ['./pruefplan-template.component.scss']
})
export class PruefplanTemplateComponent implements OnInit {
  // Code logic here
}

Template:

<h3>Prüfplan erstellen:</h3>
<p>{{this.gruppen.length}}</p>
// HTML template structure here

Model:

export interface PruefplanTemplate {
    gruppen: Gruppe[];
}

export interface Gruppe {
    // Interface definition
}

export interface Pruefung {
    // Interface definition
}

I could use some guidance from those more experienced with FormArray!

Appreciate your assistance! [1]: https://i.sstatic.net/hEAGL.png

Answer №1

Whenever utilizing a FormArray, it is important to always use a "getter" to retrieve the formArray. If we have a formArray of FormArray, we cannot use a "getter" and must instead use a function with an index.

Therefore, you should have

get groups()
{
    return this.form.get("groups") as FormArray;
}

getTests(index:number)
{
   return this.groups.at(index).get('tests') as FromArray
}

Now, as per usual,

<form [formGroup]="form">
  <div formArrayName="groups">
     <div *ngFor="let group of groups.controls; let i=index" [formGroupName]="i">
         <input formControlName="testSequence">
         ....
 
         <!-- Note that the constructor for the inner part is the same
             but we use getTests(i) -->
         <div formArrayName="tests">
             <div *ngFor="let group of getTests(i).controls; let j=index" 
                                                              [formGroupName]="j">
                <input formControlName="description">
                 ....
             </div>
         </div>
     </div>
  </div>
</form>

Answer №2

To utilize the individual pruefungen formArray from the grouppeForm local property, you would need to access it like this:

 <ng-container *ngFor="let pruefschritt of gruppeForm.get('pruefungen').controls;
    let j = index">
  ....
 </ng-container>

Answer №3

Just In: take a look at the input from @akotech


The main issue lies in specifying pruefungen as a FormArray rather than a ForControl, as demonstrated below:

addPruefplanGruppe() {
    const gruppeForm = this.fb.group({
      prueffolge: [100, Validators.required],
      name: ['', Validators.required],
      pruefungen: this.fb.array([]). // <---- pay attention to this line
    });

    this.gruppen.push(gruppeForm);
  }

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

Is there a way to incorporate TypeScript type definitions into a JavaScript module without fully transitioning to TypeScript?

Although the title may be a bit confusing, it encapsulates my query in a succinct manner. So, here's what I'm aiming to achieve: I currently have an npm module written in JavaScript, not TypeScript. Some of the users of this module prefer using ...

The use of a variable occurs prior to it being assigned through the fetch operation

While working on my function, I encountered an error message in Typescript specifically pointing to the second last line: The error stated that 'organizationInfoResponse' is being used before it is assigned. I'm unsure about how to addres ...

What is the best way to insert values from an array into a row?

Is there a way to insert values from an array into separate cells in exceljs? I attempted the following approach: const columns = ['string', 'string2', 'string3']; for(let i=0; i < columns.length; i++) { workSheet.get ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

Retrieving image data from an HTML element within an Angular app and then transmitting it to a REST server

My goal is to extract an imagedata from an html object in my Angular application (using Typescript, not JavaScript) and send it to my REST server using a service function called set_Image. Everything seems to be working fine so far, as I am able to retrie ...

Enhancing Error Handling in Node.js with TypeScript Typing

Currently, I am working with NodeJs/express and Typescript. When making a request, the compiler automatically understands the type of (req, res), requiring no additional action on my part. UserRouter.post('/user/me/avatar', avatar, async (req, ...

Sending an email using Angular is a straightforward process that involves utilizing the built

I need help figuring out how to code a function in Angular or TypeScript that will open Gmail when a specific email address is clicked. I've tried different methods but haven't been successful so far. ...

Using Typescript with React to pass a class as an argument to an external function

How can I effectively reuse functions as methods across different React classes in Typescript, ensuring compatibility and proper typing? I am trying to achieve something similar to the following... // function to be reused across classes const func = (cl ...

Guide on accessing model or view variables in Angular 4 to enable bidirectional data binding

I need to retrieve the value of a textarea in the component class by triggering a button click function. HTML <div class="container"> <div class="row"> <div class="col-lg-4 col-sm-12"> <textarea class="form-control" p ...

Angular2 Collaborative Module

Hey, I've been wondering about something. So, I have a bunch of components that I want to use in various parts of my application. However, rather than loading all these components right from the start, I'd prefer to load them on demand (lazy load ...

How can Vue Router be integrated with Vue.JS SSR?

Despite reading up on SSR documentation, I am struggling to make it work (I feel lost). I created the project with Vue CLI using 'vue new frontend'. I opted for typescript and configured all settings in package.json. Additionally, I am utilizing ...

Securely connecting Angular front end with NodeJS backend server using HTTPS encryption

I am currently using a frontend built with Angular 7 and ngx-admin, along with a backend developed in nodeJS and Express. The issue: The Angular frontend uses HTTPS to communicate with the backend via HTTP. This has caused the following problem: Mixed Co ...

Apply the functionality of a method() from component A to component B

Here is the code snippet I am working on: In this code, a function has been implemented to add two buttons to a component. Please note that this is purely HTML code. editFunction = "editRole()"; getActions(Dropup) { return '<div class=" ...

The error message in TypeScript is indicating that the property 'x' is not found in the type '{}', which is required for a computed key

Description of a Typescript fragment: enum Field { age, bugs, } interface Foo { number_age: number; number_bugs: number; } function createFoo():Foo { let obj = {}; let index = 0; for (let key in Field) { obj['numb ...

The Sharepoint web part or react app is encountering an error where it is unable to find the property 'show' within the type 'Readonly<{}>'

I haven't worked with React in a while, especially not in sharepoint. I used the yeoman generator to create a basic react app and now I'm struggling to connect the state. The code below is throwing this error: Property 'show' does not ...

Changing the positions of objects on a resized HTML Canvas

I am currently developing a tool that allows users to draw bounding boxes on images using the Canvas and Angular. Everything was working smoothly until I encountered an issue with zooming in on the canvas causing complications when trying to draw bounding ...

Merging classes from several files into a unified namespace in typescript

When working with typescript, my goal is to instantiate a class by using its name as a string. After some research, I discovered the following approach: const googlecommand = Object.create((Commands as any)['GoogleCommand'].prototype); This lin ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

Having difficulty transmitting data through SocketIO in NodeJS

My current project involves sending streams of data through SocketIO sockets. I'm working on a Node TS application that will handle large files, so the standard Buffer object won't cut it. Here's the code I have so far: Client Side socket. ...

"Recurring issue of service methods triggering multiple times with the implementation of the updated createEffect pattern in Ngrx

After transitioning certain feature Effects to the new createEffct() pattern, I noticed that all of the service requests they trigger are now appearing twice in my console output. Here's the action: export const getSetting = createAction( '[P ...