Generating objects when a form is submitted using TypeScript in Angular 7

I am currently working on creating 2 distinct objects upon form submission. Below you'll find the code snippet:

test.html

<form [formGroup]="gamificationForm" (ngSubmit)="onSubmit()">

<div *ngFor="let medal of medalResponse; let iMedal=index" class="row col-lg-12 mtop-custom-10 medal-level-point-config">
      <input type="hidden" class="point-text" [(ngModel)]="medal.medalId" formControlName="medalId" />
      <div class="col-lg-4 col-6">
        {{medal.medalName}}
        <input type="hidden" class="point-text" [(ngModel)]="medal.medalName" formControlName="medalName" />
      </div>
      <div class="col-lg-4 col-6">
        <input type="number" class="point-text" [(ngModel)]="medal.points" formControlName="points" />
      </div>
    </div>

<button class="custom-btn-class" name="submit" type="submit">Save</button>

</form>

Typescript:

    gamificationForm = this.fb.group({
    medals: this.fb.group({
      medalId: [''],
      medalName: [''],
      points: ['']
    })
  });

onSubmit() {
    console.warn(this.gamificationForm.value);
}

JSON:

It displays the last set of values from the loop both in the HTML page and JSON output.

Answer №1

To meet your specific needs, you have the ability to transform this JSON value:

convertValue(value) {
  return [
     {
       Category: [
         {
          "id-0":value.id-0,
          "name-0":value.name-0,
          "data-0":value.data-0
         },
         ....
       ],
       Item: [
         .....
       ]
     }
  ]
}

Answer №2

Regrettably, I have yet to tackle this task using Template-driven Forms. However, here are my thoughts:

To achieve the desired outcome, you should organize your fields into arrays named Level and Medal. Wrap your *ngFor loop within a

<ng-container formArrayName="Level">
container and give it a try.

Make sure each *ngFor specifies the location of the FormArray, although you may need to experiment to determine if the formArrayName directive handles this for you.

Happy coding with Angular!

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

Retrieve data from external URL using API

I am encountering a captchas page when attempting to retrieve JSON data from a URL through my API. Even though I am trying to access an array of JSON data containing openPrice, highPrice, price, and lowPrice, all I seem to get is a captcha form instead of ...

The Chrome Extension Javascript popup appears to be empty

Feeling a bit lost on my first attempt at creating a chrome extension. Check out my manifest.json below: { "manifest_version": 2, "name": "Get Offensive Wallpapers", "version": "1.0", "permissions": [ "tabs", "http://*/*", "https://*/*" ], ...

Issue with displaying value upon component initialization

I have a numeric value that needs to be displayed immediately upon the component loading. The value is calculated by multiplying a drop-down selection with another stored value in a cache. Take a look at my code snippet: ctc = 50000; ngOnInit() { ...

Angular2 is throwing a TypeError, stating that OrbitControls is not a valid constructor

Currently, I am delving into the world of angular2 and three.js. Here is how my angular cli configuration looks like. Inside package.json: "three": "^0.81.2", "three-stl-loader": "^1.0.4", In the angular.cli.json: "../node_modules/three/build/thr ...

Creating a function that can return two separate data types depending on whether optional input is provided

Take a look at this function: function useCustomElement<T extends HTMLElement>(ref?: React.RefObject<T>) { const elementRef = ref ? ref : useRef(null) const [value, setValue] = useState(false) // perform some operations... return ref ...

Is there a way to ensure that my variable is utilized consistently across the entire method?

I'm encountering an issue when trying to print out the value of an int variable after my for loop. The error message states that 'i' is not recognized as a variable. How can I resolve this? for (int i = 1; i < ar.length; i++) { } System. ...

How to retrieve data from a nested object in Angular templates

I am working with a "post" object that has an "author" property, linking each post to the author who created it. The "author" property is a nested "user" object with a "name" property. My goal is to access the "name" of the user associated with a specifi ...

Angular service worker does not start automatically unless an interval is specified

After deploying my SPA to production, I'm looking for a way to automatically reload the page whenever there's an update. Setting an interval to check for updates every X minutes doesn't seem like the most efficient solution. Does anyone have ...

Using Python's pandas library, transform a JSON column containing item details into individual rows

After importing a JSON file into pandas, I encountered the following structure: data = [ { 'order_id': 1 , 'line_item': [{'id': 11, 'price':34.1},{'id': 22, 'price':53.1}] }, ...

The NgRx Store encountered an error: Unable to freeze

I am currently developing a basic login application using Angular, NgRx Store, and Firebase. I have implemented a login action that is supposed to log in to Firebase and store the credentials in the store. However, it seems like there is an issue in my imp ...

Generating a list of prime numbers using a pre-defined function in Python

In my Python code, I have a function named prime_sieve(N) that assigns values of 0 or 1 to numbers based on whether they are prime or not. The issue lies in another function below this one, which is: import numpy as np def prime_sieve(N): nums = np.ara ...

Navigating the Command Prompt following the compilation of ng serve

Upon setting up a new Angular 5 project, installing the necessary tools including Angular CLI and Node.js, I successfully ran ng serve via command prompt. However, when attempting to install Bootstrap through the command prompt, it seemed unresponsive. Wha ...

Implement functionality to update the user interface with raw data received through Bluetooth serial communication

I've been utilizing the plugin https://github.com/don/BluetoothSerial to handle my Bluetooth connection with a HC-06 module on an Arduino Leonardo. Everything is functioning well, except for an issue I am encountering with the mobile application. Here ...

Is the Angular Library tslib peer dependency necessary for library publication?

I have developed a library that does not directly import anything from tslib. Check out the library here Do we really need to maintain this peer dependency? If not, how can we remove it when generating the library build? I have also posted this question ...

What is the best way to preserve a web response in a file?

I am currently facing an issue with saving a JSON web response in a file. Although I am able to successfully create and save the file, the content of the web response is not being captured. The file only contains: [object Object] Below is my component cod ...

Error: Unable to access the 'filter' property as it is undefined. TypeError occurred

findLoads(){ if(this.loggedInUser.userFullySetupFlag === 0 || this.loggedInUser.businessFullySetupFlag === 0){ swal( 'Incomplete Profile', 'To find loads and bid, all the details inside User Profile (My Profile) and Business Profil ...

The declaration file for the 'react-tree-graph' module could not be located

I have been working on incorporating a tree visualization into my react project. After adding the 'react-tree-graph' package and importing the Tree module, like so: import Tree from 'react-tree-graph' I encountered the following error ...

Exploring JSON array for values with stdClass nested subarrays

This JSON snippet is a segment of order data from the WooCommerce APIv2 get_order() function. Within the [meta], there are details about product variations chosen by the customer. [meta] => Array ( [0] => stdClass Object ( [key] => pa_size [l ...

Contrasting `Function` with `(...args: any[]) => any`

Can you explain the difference between Function and (...args: any[]) => any? I recently discovered that Function cannot be assigned to (...args: any[]) => any. Why is that so puzzling? declare let foo: Function; declare let bar: (...args: an ...

Exploring validation methods for Request JSON and JSON schema in Flask

When working with the flask-restplus API, I find myself needing to validate the request JSON data. I have already defined a request body schema using api.model. Essentially, I need to ensure that the input JSON data passed to the API function is validated ...