Retrieve the formcontrolname property of a FormGroup within a FormArray

I am currently facing an issue with my code. In my FormGroup, I have a FormArray containing 3 FormControls. My goal is to iterate through the FormArray and display the values of each control in a form. However, I am unsure about what to use for the formControlName.

This is my FormGroup:

fg: FormGroup = new FormGroup({
    properties: new FormArray([])
  }); 

When adding the FormControls to my FormArray using data from dataArray, this is how it's done:

let formArray = this.fg.get('properties') as FormArray;
    for(let property of dataArray){
      const userPropertyGroup = new FormGroup({
        user_id: new FormControl("", Validators.required),
        name: new FormControl("", Validators.required),
        value: new FormControl("", Validators.required),
      });

      formArray.push(userPropertyGroup); 

To set the values in the FormArray:

 for(let i = 0; i < dataArray.length; i++ ){
      formArray.controls[i].setValue({
          user_id: dataArray[i].user_id,
          name: dataArray[i].name,
          value: dataArray[i].value,
        })
    }

Now, I aim to iterate through and display all the values in the form. While {{property.value.name}} successfully fetches the values of each property in the array, I am uncertain about the formControlName field. What should be placed there?

 <form [formGroup]="fg" >
    <table *ngFor="let property of fg.get('properties')['controls']" class="full-width">
        {{property.value.name}}
      <tr>
        <td>
          <mat-form-field class="full-width">
            <input matInput formControlName="?????" placeholder="User id">
          </mat-form-field>
        </td>

Despite consulting various similar questions on StackOverflow and trying out the example provided in the Angular docs, I have yet to find a solution. Any assistance would be greatly appreciated. Thank you!

Answer №1

To properly format your html, follow the structure below:

<form [formGroup]="fg">
  <ng-container formArrayName="properties">
    <div *ngFor="let property of properties.controls; let i = index"> <!-- Loop through FormArray controls -->
      <ng-container [formGroupName]="i"> <!-- Each control within FormArray is a FormGroup -->
          <input formControlName="user_id" type="text" />
          <input formControlName="name" type="text" />
          <input formControlName="value" type="text" />
      </ng-container>
    </div>
  </ng-container>
</form>

Create a getter in your ts component file to access the properties FormArray:

get properties(): FormArray {
  return this.fg.get('properties') as FormArray;
}

Note: The HTML does not include specific CSS classes or Angular Material components for simplicity. ng-container was used for clarity, adjust elements based on your requirements.

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

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

Utilizing a Typescript class interface does not maintain the original method types

Struggling to define a Typescript interface and implement it in a class. The issue lies in the method signatures of the interface not being applied to the class as expected. Below is a simplified example: export interface Foo { bar(value: string): voi ...

Update the collapse panel content using ng-repeat

Managing a list of projects with multiple tasks can be quite challenging. One approach is to utilize a collapse panel where each project serves as the title, and the tasks are displayed within the content section. However, one common issue faced in this se ...

Launching the Angular2 application

I created an Angular 2 application and now I am looking to deploy it. Currently, my root folder contains: HTML files JS files (compiled from TypeScript) CSS files (compiled from SCSS) /node_modules/ directory /bower_components/ directory The last two d ...

Leverage the SVG foreignObject Tag within your Angular 7 project

I am currently working with Angular 7 and trying to use the SVG foreignObject to embed some HTML code. However, I am encountering an issue where Angular fails to recognize the HTML tags and throws an error in the terminal. Below is the code snippet: &l ...

Using Jimp to load a font and retrieve its Base64 representation

I am currently working in Angular with Jimp, attempting to overlay text onto an existing image. However, the image is not updating as expected. const Jimp = require('jimp') var _this = this; Jimp.read("assets/TimeLine.png").then(function ( ...

Tips for displaying multiple pages of a Power BI embed report on Mobile layout within the host application

I created a Power BI embed application using Angular on the frontend and C# on the backend. The issue I am facing is that when viewing Power BI reports in mobile layout, reports with multiple pages only show the default page and do not display the other pa ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

What is the best way to ensure that the first tab is always pre-selected among dynamic tabs?

I'm currently working on an angular 4 project and I need to implement a feature where there are three checkboxes. When the first checkbox is selected, a new tab should be dynamically created. So, if all three checkboxes are selected, there will be thr ...

Angular child component displaying of table data is not looping properly

Currently, I am using Angular 13 along with Bootstrap 3 to develop an application that consists of two main components: form-component (dedicated to inputting user details) and list-component (designed to showcase all data in a table format). Within the HT ...

Working with Typescript and JSX in React for event handling

I'm currently facing an issue with updating the state in a React component I'm developing using TypeScript (React with Addons 0.13.3, Typescript 1.6.0-dev.20150804, definition file from ). /// <reference path="react/react-addons.d.ts" /> i ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

Angular in conjunction with socket.io does not immediately show messages on screen

I am currently working on developing an instant messaging app (chat) using socket.io and Angular. I have two main files: index.html and index.js as shown below. The chat functionality is working well, but I am facing an issue where the messages do not appe ...

Tips for making the background image fit perfectly within a div element

I have a calendar div that I want to customize with a background image and text. How can I achieve this? Here is my code: .calenderArrivalDiv{ margin-top: 15%; margin-bottom: 1%; background-image: url("im ...

"Enhance your data display with PrimeNG Table components and easily customize layouts

I am currently utilizing PrimeNG version 12.0.1 along with its Table component to showcase data within my Angular application. In a separate @Component, I have included the <p-table> in the HTML template. Within the <p-table>, there are variou ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

An issue occurred while trying to run Ionic serve: [ng] Oops! The Angular Compiler is in need of TypeScript version greater than or equal to 4.4.2 and less than 4.5.0, but it seems that version 4

Issue with running the ionic serve command [ng] Error: The Angular Compiler requires TypeScript >=4.4.2 and <4.5.0 but 4.5.2 was found instead. Attempted to downgrade typescript using: npm install typescript@">=4.4.2 <4.5.0" --save-dev --save- ...

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

Testing the change in states with resolve functions in AngularJS

Testing in AngularJS is still new to me, and I'm currently working on writing tests for a $stateProvider that I've set up like this: angular.module("app.routing.config", []).config(function($stateProvider, $urlRouterProvider) { $stateProvider. ...

What is the reason behind the inability of the Angular/TypeScript HTTP GET method to accept a JSON object as a parameter

EXAMPLE 1 passJSONObj(){ let name = 'user names', let email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a2a4b2a5b2bab6bebb97b3b8bab6beb9f9b2afa3">[email protected]</a>&ap ...