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

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

Utilizing Regular Expressions as a Key for Object Mapping

Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem. This is how I typica ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

React waitforelement fails to work in conjunction with asynchronous calls

I am currently experimenting with a straightforward login form that includes an asynchronous call in React using TypeScript and classes. Here is how my component appears: import * as React from 'react'; import { LoginService } from './servic ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...

Generate a fresh class instance in Typescript by using an existing class instance as the base

If I have these two classes: class MyTypeOne { constructor( public one = '', public two = '') {} } class MyTypeTwo extends MyTypeOne { constructor( one = '', two = '', public three ...

My AngularJs code seems to be throwing some errors

I recently started learning Angularjs and here is the code I have written: <!DOCTYPE html> <html> <head> <title>ng-Messages Service</title> <script src='https://ajax.googleapis.com/ajax/libs/jquery ...

Tips for changing the background color depending on the value

I am creating a table displaying the results of a tournament. Each team's final placement and original seeding will be listed. I plan to include a small bubble next to each team showing how their final placement compares to their initial seeding. To v ...

Why use rxjs observables if they don't respond to updates?

I have an array of items that I turn into an observable using the of function. I create the observable before populating the array. However, when the array is finally populated, the callback provided to subscribe does not execute. As far as I know, th ...

Optimal method for efficiently caching data when toggling between list view and detail view within Angular 12

In my Angular App, I have implemented two components - a list view and a details view. Users can switch between these components, both of which utilize multiple async pipes. To minimize the number of http requests to the backend, I decided to cache data u ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

Type 'Partial' cannot be assigned a value when combining interfaces with generic types

Consider the following scenario: class Table<ValuesType extends DefaultTableValues = DefaultTableValues>{ public values: ValuesType; constructor(initialValues:ValuesType) { this.values=initialValues; } public set(newValues:Pa ...

"Error message: The term 'subscribe' is not recognized in Angular

Recently, I started learning Angular and have been following Angular6 tutorials on YouTube here. I encountered an error while working on the project. My goal is to display a list of employees below the existing lists, and I am currently troubleshooting t ...

Automatically log into Google using Angular with Angularx-Social-Login

Utilizing Google sign-in and Angularx-Social-Login to authenticate users has been successful for me. However, I am facing an issue where users have to log in again whenever they reload the page or open a new tab, despite setting autologin: true. I have imp ...

Utilizing Array Notation in Typescript to Retrieve Elements from Class

In my programming project, I am working with two classes: Candles and Candle. The Candles class includes a property called list, which is an array containing instances of the Candle class. class Candles { public list: Array<Candle>; } class Candl ...

Send the user's context id as a header when making a request to a REST

In my current setup, I have implemented two applications - a Laravel REST API and an Angular front end, each residing on different domains. This is a multi-tenant application where users can be associated with one or multiple organizations and have the abi ...

What are some ways to lazily load directives in AngularJS?

Currently, I am exploring the capabilities of angularjs and aiming to dynamically load directives only when they are required instead of loading all of them initially on the page. My focus is on creating custom directives for the plugins that I use frequen ...

"Encountering a 400 bad request error when making a Graphql POST

Seeking assistance with my graphql code. I have included the service and component files below. I am currently new to graphql and not utilizing the apollo client; instead, I am attaching a query on top of the HTTP POST call to send requests to the graphql ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Updating form fields within nested forms using the FormBuilder array

The recommended method to change nested values according to the API documentation is using patchValue. For example, myForm.patchValue({'key': {'subKey': 'newValue'}}); But what if we need to change values in a nested array, ...