Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI:

Here is the JSON Object :

items={"departure":"New York","arrival":"California","stations":[{"station":"toto"}]}

On the user interface, I have a submit button that may not be visible but can execute this function:

save(){
  console.log(Json.stringify(this.myForm.value))
 }

The generated JSON Object is as follows:

{"tabls":[{"price":20}]}

Currently, only the first price is displayed. However, I would like all prices generated in the UI to be shown, resulting in the following JSON:

{"tabls":[{"price":20},{"price":10}]}

How can I make this happen?

Below is the HTML code snippet provided:

<div formArrayName="tabls">
                    <div *ngFor="let myGroup of myForm.controls.tabls.controls; let i=index">
                      <div [formGroupName]="i">

                        <div class="row">
                          <div class="col-sm-4" >
                              <div   >
                                  <div class="inner-addonx left-addon header-search" style="float:left;margin-right: 4px;">
                                    <i class="glyphicon  markerx" style="border: 5px solid #FED141"></i>
                                  </div>
                                <span >{{items.departure}}</span> 

                              </div>
                          </div>
                          <div class="col-sm-1" ><img style="    width: 32px;    height: 22px;" src="../assets/img/arrow.svg" ></div>
                          <div class="col-sm-4" >
                              <span *ngIf="items.stations.length > 0">
                                  {{items.stations[0].station}}
                              </span>
                              <span *ngIf="items.stations.length === 0">
                                  {{items.arrival}}
                              </span>
                          </div>

                          <div class="col-sm-3" >
                              <div class="input-group " >

                                  <input type="number" formControlName="price"  value="1000" min="0" step="1" [attr.id]="'textbox'" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" /> 
                                  <span class="input-group-addon">Dhs</span>
                            </div>
                          </div>
                        </div>

                        <hr/>
                        <div class="row">
                            <div *ngIf="items?.arrival && items?.departure">
                                <div class="col-sm-4">
                                    <div  style="">
                                        <div class="inner-addonx left-addon header-search" style="float:left;margin-right: 4px;">
                                            <i class="glyphicon  markerx" style="border: 5px solid #63a599"></i>
                                        </div>
                                        <span>{{items.departure}}</span> 

                                  </div>
                                </div>
                                <div class="col-sm-1" >
                                    <img style="    width: 32px;    height: 22px;" src="../assets/img/arrow.svg" >
                                  </div>
                                <div class="col-sm-4" >
                                    <div  style="">
                                        <div class="inner-addonx left-addon header-search" style="float:left;margin-right: 4px;">
                                            <i class="glyphicon  markerx" style="border: 5px solid #F53F5B"></i>
                                        </div>
                                        <span>{{items.arrival}}</span>
                                    </div>
                                </div>

                                <div class="col-sm-3" >
                                    <div class="input-group ">

                                        <input type="number" formControlName="price"  value="1000" min="0" step="1" [attr.id]="'finalprice'" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="c2" />
                                        <span class="input-group-addon">Dhs</span>


                                    </div>
                                </div>

                            </div>
                        </div>
                      </div>
                    </div>

                  </div>

Typescript code segment:

ngOnInit() {
   this.myForm = this._fb.group({

   tabls: this._fb.array([
    this.initArray2()
   ]),
 })
 }
initArray2() {
   return this._fb.group({
   price: [''],
  });
 }

Answer №1

Make sure you have 2 inputs with the formControlName="price", as it will replace the previous value.

Answer №2

initialize() {
   let container = this.createContainer([{cost:0},{price:0}]);
   this.formData = this._fb.group({
   tables=container
   }):

}

createContainer(data: any[]) {
    //for each data, we generate a fbGroup 

    const array = myArray.map(data => {
      return this.fb.group({
        "Id": [data.Id], //certain controls can be skipped
        "teamName": [data.teamName],
        "amount": [data.amount],
      });
    });
    //Return an array of fbGroup
    return this.fb.array(array);
  }

For more information and examples, visit Binding an input field to a property in an observable object - Angular or explore similar links for additional insights.

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

Implementing new updates to an object without affecting existing values in Vue.js 2

I am currently facing an issue with updating values for an object received in a payload before saving it to the database. Despite making changes, the new values are not being persisted correctly. I am utilizing Vue.js 2 for this task. How can I effectively ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

I am looking to dynamically alter the CSS background URL using JavaScript

Currently, I am looking to update the background image url using JavaScript. Most tutorials I've come across involve having the image downloaded on the desktop and then providing its path. However, in my scenario, the user will input an image link whi ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

Tips for creating a helper function that returns a promise for a React hook function

So, I have this React functional component that makes use of both the useState and useEffect hooks: import React, { useState, useEffect } from 'react'; import { requestInfo } from './helpers/helpers'; const App = () => { const [pe ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

How can you verify the correctness of imports in Typescript?

Is there a way to ensure the validity and usage of all imports during the build or linting phase in a Typescript based project? validity (checking for paths that lead to non-existent files) usage (detecting any unused imports) We recently encountered an ...

Changing the color of a div element dynamically with JavaScript

Is there a way to improve the code below so that the background color of this div box changes instantly when clicked, without needing to click twice? function updateBackgroundColor(platz_id) { if(document.getElementById(platz_id).style.backgroundCol ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

Adobe Acrobat does not run JavaScript code in documents that are submitted for electronic signatures

Lately, I have been experiencing issues with pdfs that contain embedded javascript. The strange thing is that the javascript functions perfectly in the Acrobat Pro DC app but fails to execute when the document is sent for signature. To troubleshoot, I cre ...

When we typically scroll down the page, the next section should automatically bring us back to the top of the page

When we scroll down the page, the next section should automatically bring us back to the top of the page without having to use the mouse wheel. .bg1 { background-color: #C5876F; height: 1000px; } .bg2 { background-color: #7882BB; height: 1000px; } .bg3 ...

Encountering difficulty in reaching the /login endpoint with TypeScript in Express framework

I'm currently working on a demo project using TypeScript and Express, but I've hit a roadblock that I can't seem to figure out. For this project, I've been following a tutorial series from this blog. However, after completing two parts ...

Using Angular UI Router to Access $scope Beyond the Scope of the UI View

Looking for a way to access $scope outside the UI view in my todo app. The structure is simple, with three panels as shown in this design For the full code, visit here I need to access the to-do detail on the third panel using $rootScope, which currently ...

Tips for making an image fill the entire screen with a header using React Navigation

My screen includes an image and I would like to capture the full-size screen with the header displayed. However, using position: "absolute" does not properly wrap the header, and setting header: null is not an option since I still want the back button to b ...

What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success. Javascript function sendFormData(fD) { var urls = fD ...

Modifying the value of a property in one model will also result in the modification of the same

As a beginner with Vue, I am looking to allow users to add specific social media links to the page and customize properties like text. There are two objects in my data - models and defaults. The defaults object contains selectable options for social media ...

What is the best way to retrieve localstorage information within the getStaticProps function in next.js?

Having trouble retrieving local storage data with the following code. localData = { id: localStorage.getItem("id"), token: localStorage.getItem("token"), }; This snippet is housed within a function called getStaticProps ...

Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following: "questions": [ { "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", "id": 0, "poster": "Chelsea Vang", "question": "Ex ex elit cu ...

The datetimepicker is not functioning properly

I'm experiencing an issue with the datetimepicker where it doesn't display a calendar when I click the icon. Interestingly, the Chrome browser isn't showing any errors in the development console. <script src="Scripts/jquery-2.1.1.min.js ...