How can I access a nested FormArray in Angular?

I have a situation where I am trying to access the second FormArray inside another FormArray. Here is an excerpt from my component:

registrationForm = new FormGroup({
    registrations: new FormArray([this.patchRegistrationValues()])
  });

patchRegistrationValues(): FormGroup {
    return new FormGroup({
      //some other FormControls
      setDate: new FormArray([this.patchSetDate()]),
    });
  }

get registrations(): FormArray {
    return this.registrationForm.get('registrations') as FormArray;
  }

I am struggling with how to access the setDate for populating it. I attempted this method, but it did not work:

get setDate(): FormArray {
    return this.registrations.get('setDate') as FormArray;
  }

Can anyone provide guidance on how to achieve this? Is an index required?

UPDATE

Apologies for the delay in response, here is the HTML snippet I am working with:

<thead>
    <tr>
        <!-- TODO: add translation to table -->
        <th>Project</th>
        <th>Date</th>
        <th>Buttons</th>
        <th nzAlign="center" class="fit">
            <app-add-btn (click)="addRegistrationRow()" label="{{'common.add' | translate}}"></app-add-btn>
        </th>
    </tr>
</thead>
<tbody formArrayName="registrations">
    <tr *ngFor="let reg of registrations.controls; let i = index" [formGroupName]="i">
        <td>
            <!--FormControl goes here like an input-->
        </td>
        <td>
            <ng-container *ngFor="let date of setDate.controls let ind = index" [formGroupName]="ind">
                <!--Not so sure about this part, any input I set here doesn't show in the page, it's like a blank cell-->

            </ng-container>
        </td>
        <td nzAlign="center" class="fit">
            <app-delete-btn (click)="removeRegistrationRow(i)"></app-delete-btn>
            <app-add-btn (click)="addSetDateRow()" label="{{'common.add' | translate}}"></app-add-btn> <!-- this doesn't work -->
        </td>
    </tr>
</tbody>

Once again, apologies for the delay!

Answer №1

To access the parent FormArray, you must provide the corresponding index.

getSetDateControlFromRegistrationForm(registrationIndex: number): FormArray {
  return (this.registrations.controls[registrationIndex] as FormGroup)
    .get('setDate') as FormArray;
}

It is important to note that without passing the index as a parameter, the method cannot function as intended.


Revised Guideline

Referring to the HTML template provided, the following steps are required:

  1. Create a wrapper for

    formArrayName="setDate"

  2. Utilize the mentioned method to iterate through the controls of the setDate FormArray.

  3. The innermost part consists of the FormGroup along with its FormControl(s).

<ng-container formArrayName="setDate">
  <ng-container
    *ngFor="
      let date of getSetDateControlFromRegistrationForm(i).controls;
      let ind = index
    "
  >
    <!-- Form Group in each setDate Form Array -->
    <div [formGroupName]="ind">
      <input formControlName="i" />

      <input formControlName="date" />
    </div>
  </ng-container>
</ng-container>

Check out the demonstration on StackBlitz

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

unnecessary files in the node_modules directory in Rails

I am a beginner in Node.js and unfamiliar with npm and modular JavaScript. After using the browserify-rails gem, I noticed that there are multiple files from a GitHub repo stored in the node_modules folder after running npm install. Since I only require ...

Can you explain the distinction between the two methods of coding in jQuery?

1, $.each(a,f); 2,$("a").each(f); I understand the purpose of the last line, where it selects all <a> elements in the document and then calls the each() method to invoke function f for each selected element. However, I am unsure about the meani ...

Looking to properly align the items in your navbar? Discover how you can achieve this effortlessly with HTML and the

I'm trying to create a navbar with the logo on the right side and other items like Home, Contact Us, About, etc. aligned towards the left. However, when I attempt to align the items, they all shift completely to the left. I want to evenly space them w ...

Check the value of a single bit in JavaScript: Is the bit on (1) or off (0)?

Is there a way in JavaScript to determine if a single Bit is On (1) or Off (0)? function isBitOn(number, index) { // ... ? } // Example: let num = 13; // 1101 isBitOn(num, 0); // true 1 isBitOn(num, 1); // false 0 isBitOn(num, 2); // true 1 isBit ...

Tips for continuously running a loop function until retrieving a value from an API within a cypress project

Need help looping a function to retrieve the value from an API in my Cypress project. The goal is to call the API multiple times until we receive the desired value. let otpValue = ''; const loopFunc = () => { cy.request({ method: &ap ...

Steps to retrieve hexadecimal addresses sequentially

Can anyone recommend a module or script that can generate sequential 64-bit hex addresses like the following: 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000001 00000000000 ...

tips for exporting database information to an excel file with the help of ajax request and javascript

Recently, I built an application using NDWS with sapui5 _javascript. Within the application, there is a table that contains data synced with the server's database. My goal is to retrieve this data from the table and export it to an Excel document. Her ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

How to successfully pass a Bootstrap dropdown value back to Flask

I need assistance with extracting a selected value (player) from a dropdown menu. The goal is to send this 'player' value to Flask upon selection, and then render the corresponding player's image on the website. HTML: <form method="P ...

Picture cannot reemerge with SetTimeout

Browsing Experience: Users will simply tap on an image (group of spots) to make it disappear from the screen. Upon clicking the image, it will smoothly fade out. However, if the user does not interact with the image, a new one won't show up after 10 ...

I'm encountering an error with the *ngIf directive in my Angular reactive form - any ideas on

Despite my reputation, I have a question that is causing me some confusion. I am trying to create a reactive form using an example on Stackblitz. While everything seems fine in Stackblitz and the code works correctly there, I encounter an error in VS Code ...

What methods can I use to accomplish the transformation of superimposed images?

Struggling with transforming a content box on my webpage. I have a div containing three overlapping images positioned using Grid, and I want to scale one of them to fill the entire div when scrolled over. While I managed to achieve this effect, I'm un ...

Passport - Pairing Plan "Error|The username provided for sign_request() is not recognized"

Currently experimenting with duo in node.js using passport to test its implementation in an application....Utilizing a passport-duo strategy and encountering issues when trying to apply the example provided in my own project. The GitHub repository for pass ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Mastering Puppeteer: Tips for Successfully Submitting Forms

Can you use puppeteer to programmatically submit a form without a submit input? I have been successful with forms that include a submit input by using page.click('.input[type="submit"]'), but when the form does not have a submit input, focusing o ...

Ways to retrieve the key of an enum based on its value within Typescript

Here's an example of an enum: export enum Colors { RED = "RED COLOR", BLUE = "BLUE COLOR", GREEN = "GREEN COLOR" } Can you help me figure out how to retrieve the enum key based on a specific value? For instance, if I input "BLUE COLOR", ...

Encountering difficulties with displaying error messages on the Material UI datepicker

I am currently utilizing React Material UI There is a need to display an error based on certain conditions that will be calculated on the backend. Although I have implemented Material UI date picker, I am facing issues with displaying errors. import * as ...

Discovering the file system with window.resolveLocalFileSystemURL in Typescript for Ionic 3

After reviewing the documentation found on this link for the File plugin, I came across a paragraph that discusses how to add data to a log file. See the example code below: window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) ...

Why is the column width on this Tumblr page constantly flickering?

Seeking assistance with a minor issue on my Tumblr page - the content column seems to be flickering on mouseover, shifting between full width and its original programmed width. Any insight on the CSS causing this? Much appreciated! Check it out here (Dis ...

Is there a way to modify the edit button to become a save button and include a cancel button?

Is there a way to toggle between an edit button and a save button, along with a cancel option? $('#edit').click(function() { $(this).hide(); $('#save, #cancel').show(); }); $('#cancel').click(function() { $('#ed ...