Progressively cycle through each group within an array of reactive forms

My goal is to display array data in a reactive format and iterate over a group within the array based on my data. Here is an example of how my data structure looks:

{
  nombre: 'Inca Suprema'
  precios: [
    {
      precio: 16,
      variante: 'Personal'
    },
    {
      precio: 28,
      variante: 'Mediana'
    },
    {
      precio: 38,
      variante: 'Familiar'
    }
  ]
}

I want to load the array like this:

https://i.sstatic.net/Lzs7F.png

I have attempted the following code, but it returns null. When I use this.data.item.precios, I get the precios array.

component.ts

 this.formItem.addControl('precios', this.fb.array([
        this.data.item.precios.forEach(element => {
          this.fb.group({
            variante: [element.variante],
            precio: [element.precio],
          });
        })
      ]));

component.html

<div formArrayName="precios" class="col-12">
            <div *ngFor="let precio of formItem.controls['precios']['controls']; let i = index;">
              <div [formGroupName]="i" class="d-flex">
                <div class="row gx-3">
                  <mat-form-field appearance="standard" class="col-6">
                    <mat-label>Variante</mat-label>
                    <input matInput type="text" formControlName="variante">
                  </mat-form-field>
                  <mat-form-field appearance="standard" class="col-6">
                    <mat-label>Precio</mat-label>
                    <span matPrefix>S/. &nbsp;</span>
                    <input matInput type="number" formControlName="precio">
                  </mat-form-field>
                </div>
                <div class="pt-1">
                  <button class="ms-2" matSuffix mat-icon-button (click)="eliminarPrecio(i)" [disabled]="i === 0">
                    <i-tabler name="trash"></i-tabler>
                  </button>
                </div>
              </div>
            </div>
          </div>

Answer №1

Consider using the map method instead of forEach if you need to transform data into an array:

this.formItem.addControl('precios', this.fb.array(
  this.data.map(element =>
     this.fb.group({
        variante: [element.variante],
        precio: [element.precio]
     })
  )
))

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

What is the process for including headers while establishing a connection to a websocket?

After configuring a websocket topic using Spring websocket on the server side, we implemented the client side with Stomp.js to subscribe to it. Everything was functioning correctly when connecting directly to the websocket service. However, we decided to i ...

Angular 5 in conjunction with Keycloak enabling access for non-authenticated users

I have a situation where I need to implement anonymous user access in my app, and for that purpose, I am incorporating the 'keycloak-angular' library along with Angular 5. The documentation instructs me to initialize the application as shown belo ...

Issue with ngx-extended-pdf-viewer: text not appearing due to incorrect cmaps path

I have been using the most recent stable version of ngx-extended-pdf-viewer (4.1.2) along with Angular 9.1. Everything was functioning perfectly, but after building the application, certain PDF files were not displaying any text. Upon investigation, it was ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

Unable execute the Select All command in sqlite

I've been working on several queries, but unfortunately I've encountered an issue with this one that is not providing a helpful error code. The table I'm working with is 'Activity' and I simply want to select all records from it. ...

Guide on setting up component from service to display toast notifications

I am looking to implement a global toast service in my application with custom styles and HTML for the toasts. Currently, I am using ng2-toastr. For example, let's say I have a component A which contains a button in its view: <button (click)="show ...

An issue arises in TypeScript when targetting ES5 and utilizing Async Iteration, causing errors while running in the browser

After reading through the documentation on "Generation and Iteration for ES5", I implemented this polyfill: (Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator"); However, upon doing so, my browser encountered an erro ...

The traditional Angular model definition has been revamped with the implementation of web services model

I have a TypeScript model that looks like this: import * as moment from 'moment'; export class Activity { public id: number; public activityDate: string; public day: number = moment(this.activityDate).dayOfYear(); } Also, a C ...

Changes in Angular forms are considered dirty when they differ from their initial state

I am utilizing Angular to design a basic input form like the one shown below. Is there a method available for me to monitor the "true" state of whether a form field has been edited or not, even if a user reverts back to the original value? For example, w ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

Obtain text output from an Observable

After retrieving a String from the backend: String value = "{I am here}"; In my service method: getValue(): Observable<String> { return this.http.get<String>(this.myURL); } In my component, I am subscribing to this method: String myM ...

Guide to displaying loading progress during server response delay in React with TypeScript

I need to find a way to update the loading state to false once the server responds. The challenge is that the response occurs in one component, while the progress bar is located in another. To illustrate the scenario: const Form: React.FC = () => { ...

A guide on passing variables to the MUI styled function within ReactJS

Is it possible to pass a variable directly to the styled function in order to conditionally change style properties while using MUI styled function? I want to achieve something like this: borderColor: darkMode ? 'white' : 'black' const ...

What is the best way to save emitted values from rxjs?

I'm currently grappling with understanding rxjs. In my angular project, I've created a service that emits and listens to boolean values that indicate the start and completion of asynchronous operations. export class UpdateScriptRunningEventServi ...

Next.js (TypeScript) - Error: Property 'req' is not recognized on the type 'GetServerSideProps'

Currently, I am tackling a challenge involving the utilization of next-auth and attempting to access the session from within getServerSideProps. However, in order to achieve this, it is essential for me to provide the context request and context response ...

Tips for troubleshooting errors in rxjs/observable while working with web API in Angular 4

Recently, I encountered this issue in my command prompt. Despite having the latest Node.js version, I faced this error when cloning my Angular 4 project to CLI: ERROR in node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module ' ...

Is there a way for me to input an event in handleSumbit?

I am having trouble understanding how to implement typing in handleSubmit. Can someone help? It seems that the "password" property and the "email" property are not recognized in the "EventTarget" type. import { FormEvent, useState } from "react" import { ...

Adding the project license to the build in an Angular CLI project for xRay license scanning: A step-by-step guide

Our project has a unique licensing agreement specified in the license attribute within package.json. Upon running ng build, we notice that a 3rdpartylicenses.txt file is created in the dist folder containing licenses for all dependencies except our custom ...

Struggling to pass images from express to Angular6

Snippet of Node.js code app.use('/static/images',express.static(path.join(__dirname,'images'))) Folder Structure |-root | -images When attempting to fetch data in my Angular6+ application, I am utilizing the following ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...