How to populate a form array in Angular

I am currently working with Angular 8 and have an API structured like this:


{

    "no": "s01",
    "id": 1,
    "details_id": {
        "install": "Y"
        "unitprice": "100.000000000000000",
        "weight": "1.000000000000000"
        },
        "qty": 1,
        "remarks": "ok" 
}


My goal is to patch data in a format similar to the one shown below using Angular:

{
 
  "Header_img": null,
  "details": [
    {
      "install": "",
      "remarks":""
      "del_details": [
        {
          "qty": "",
          "unitprice":"",
          "weight": ""
          
        }
      ]
    }
  ]
}

  ngOnInit(): void {

    this.Form = this.fb.group({
      Header_img: [],
      podetails: this.fb.array([this.addpodetailsGroup()])
    });
  }

  addpodetailsGroup() {
    let group=  new FormGroup({
      install: new FormControl(''),
      d_details: this.fb.array([
        this.d_detailsGroup()
      ])
    }
  )
return group}

  d_detailsGroup(): FormGroup {
    return this.fb.group({
      qty: new FormControl(''), 
      "unitprice": new FormControl(''), 
      "weight": new FormControl(''), 
    });
  }

Here is the function for patching the data:


getdDetails(){
    let id = this.iddata
    this.dataService.getdetails(id)
    .subscribe((results) => {
      let datas = results["data"];
      this.dList = datas
    })
  }
  
getdetailsForQuantity(data){
  let id = data.id 
  console.log('id value data getdetailsForQuantity',id)
this.dataService.getdetailsfor(id)
  .subscribe((result: any)  => {
     this.install = result.details_id.installationrequired
     this.unitprice = result.details_id.unitprice
    this.form.patchValue({
         
         details:[{
              install: this.install
             d_details: this.unitprice
          }]

    })


})

}


Need assistance on patching data in form array? How can I use reactive forms to patch data when the backend data structure does not match the required format for submission?

Answer №1

Check out the solution provided below:

To solve this issue, you need to create a formGroup for the FormArray that corresponds with the length of the response.

If the response looks like this,

{
  "Header_img": null,
  "details": [
    {
      "install": "",
      "remarks":""
      "del_details": [
        {
          "qty": "",
          "unitprice":"",
          "weight": ""
        },
        {
          "qty": "",
          "unitprice":"",
          "weight": ""
        }
      ]
    }
  ]
}

And your form structure should be like the one below

this.form = this.fb.group({
    install: '',
    remarks: '',
    del_details: new FormArray()
});

addControltoFormArray() {
     return this.fb.group({
         qty: '',
         unitprice: '',
         weight: ''
     });
}

Now, patch the form as follows:

getdetailsForQuantity(data){
    let id = data.id; 
    console.log('id value data getdetailsForQuantity',id);
    this.dataService.getdetailsfor(id)
    .subscribe((result: any)  => {
         this.form.patch({
             install: result.details.install,
             remarks: result.details.remarks
         });
         let control = this.form.get('del_details') as FormArray;
         result.details.del_details.forEach((obj:any,index:any) => {
              control.push(this.addControltoFormArray());
              control.controls(index).patch({
                  qty: obj.qty,
                  unitprice: obj.unitprice,
                  weight: obj.weight
              });
         });
         console.log(this.form.value);
    });
}

Hope this explanation helps!

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

When using Angular 2, the `onYouTubeIframeAPIReady` function may not be able to locate the `YT` name, even if it is defined on the

As part of my efforts to track when a user pauses a YouTube video (link to the question), I have been utilizing the onYouTubeIframeAPIReady callback method in Angular2. I am facing similar challenges as discussed here and here. Following the recommendati ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

Gain insights on Stripe Webhooks with Firebase Functions and Node.js

I've been struggling to integrate Firebase functions with Stripe webhooks for listening to events. Take a look at my code: exports.stripeEvents = functions.https.onRequest((request, response) => { try { const stripeSignature = request. ...

Angular 2 - Generating ZIP files using byte arrays

Can someone provide guidance on how to save multiple files in an Angular 2 application as a zip directory, when the files are currently stored on the client side as base64 strings? The files are retrieved from a webapi as base64 strings and then converted ...

Tips for creating an observable in Angular 2

I'm having trouble declaring an observable and adding data to it in Angular 2. I've spent the last 5 hours trying to figure it out. Here's what I've attempted: this.products : Observable<array>; var object = {"item": item}; thi ...

Error: Syntax error - there was an unexpected token '.'

An error occurred with SyntaxError: Unexpected token '.' in the file path C:\Users\bruno\OneDrive\Área de Trabalho\DEV Bruno\devapi\node\src\views\layouts\layout01.ejs while compiling ejs I ...

What is the process for configuring the directive to establish a drag-and-drop area within Angular?

I am currently working on implementing a file drag and drop zone in Angular. I have created the dropzone.directive and added it to the declarations in app.module.ts. While my code compiles and launches successfully, I am facing an issue where the HTML doe ...

Adding a structure to a sub-component within Angular 6 by inserting a template

Given the constraints of this scenario, the app-child component cannot be altered directly, leaving us with only the option to interact with the app-parent component. Is there a method available that allows us to inject the template into app-child, such as ...

Is it possible to resolve the issue with error code TS7016 stating that the declaration file for module '@angular/compiler' could not be found?

After integrating SignalR into my Angular Frontend, I encountered an error with code TS7016. import { ViewCompiler } from '@angular/compiler'; Attempting to resolve the issue, I executed the command: npm i --save-dev @types/angular__compiler ...

Testing an angular component that has a required @Input is essential to ensure its functionality and

My current component has the following structure based on this advice @Component({ selector: 'app-component[required]', templateUrl: './component.component.html', styleUrls: ['./component.component.scss'] }) export class ...

Creating adaptable rows and columns with Angular Material's data table feature

My approach to rendering dynamic rows and columns using a basic table was successful: <tbody> <tr *ngFor="let row of data"> <td *ngFor="let val of row"> {{ val }} </td> </tr> </tbody> </ ...

Issue arising from the rendering of items in a Navigation Bar

I'm encountering an issue where only the last item of the navbar is being rendered even though the data appears to be correct. I've tried hard coding the data into the components but the same error persists.https://i.sstatic.net/ccEuB.png , https ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

Angular app experiences functionality issues following integration with Cordova Facebook Connect plugin

After using the Facebook connect plugin's login method and attempting to redirect to another page, Angular seems to freeze without any response. Despite trying different solutions, it remains a mystery why a Cordova plugin disrupts the functionality ...

Utilizing momentjs to convert date and time to various time zones

Within my Angular application, there is a selectbox that allows users to choose the timezone for converting a specific time. I am currently utilizing momentjs for date-time manipulations, however, I am facing an issue regarding changing the timezone of the ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Using TypeScript generics to create reusable type definitions for reducers

I have a common reducer function that needs to be properly typed. Here's what I have come up with: export interface WithInvalidRows<T extends { [K in keyof T]: InvalidCell[] }> { invalidRows: T; } interface AddPayload<S extends WithInval ...

retrieve a shared string from an array when toggled

Regarding the use of SelectionModel for mat-checkbox, a function is called on each click: toggleSelection(row) { this.selection.toggle(row); console.log("Selection"); console.log("this", this.selection.selected); this.selection.selected.f ...

What is the best way to dynamically insert rows into an Angular material table using an array of rows?

Struggling to create a material table that features dynamic headers and rows populated by an array of strings. Unfortunately, I haven't been successful in displaying the rows within the table. Check out the code here <div *ngIf="customerRespo ...

Issue encountered when attempting to run "ng test" in Angular (TypeScript) | Karma/Jasmine reports an AssertionError stating that Compilation cannot be undefined

My development setup includes Angular with TypeScript. Angular version: 15.1.0 Node version: 19.7.0 npm version: 9.5.1 However, I encountered an issue while running ng test: The error message displayed was as follows: ⠙ Generating browser application ...