Assign values to a nested FormGroup in Angular 10 based on the provided JSON object

What is the most efficient way to set values for a JSON object coming from the backend? I am familiar with manually setting values based on the key param, but are there any other optimized approaches I should consider?

//backend response
"response": {

    "senderCode": "123",
    "senderName": "test2",
    "receiverCode": "456",
    "name": "test",
    "contactnumber": "1233333333"

}
//formgroup structure

this.Form = this.fb.group({
    receiverCompanyCode: null,
    // Sender Information
    senderInformation: this.fb.group({
        senderCompanyCode: [null],
        senderName: [null],
    }),

    // Contact Information
    contactInformation: this.fb.group({
        name: [null, Validators.required],
        telephone: [null, Validators.required],
    }),
});

Answer №1

Perhaps this could be of assistance to you

let data = {
      title: 'example',
      number: '5555555555'
};
this.formData.setValues(data);

Answer №2

To properly input the data into the form, you will need to manually map the values like this:

const mappedValues = {
receiverCompanyCode: response.receiverCompanyCode,
    senderInformation: {
        senderCompanyCode: response.senderCompanyCode,
        senderName: response.senderName,
    },
    contactInformation: {
        name: response.name,
        telephone: response.telephone,
    }
}
this.Form.patchValue(mappedValues);

Alternatively, you can adjust the FormGroup structure and directly patch the response values like so:

this.Form = this.fb.group({
    senderCode: [null],
    senderName: [null],
    receiverCode: [null],
    name: [null],
    contactnumber: [null]
});
this.Form.patchValue(response);

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

"Encountered a duplication issue while attempting to create a unique name by combining input from the textbox with the original file name using a combination of

Hey there, I'm looking to create a new name by adding the name from a text box to an original file. script.js angular.module('signin').service('fileUpload', ['$http', function ($http) { this.uploadFileToUrl = funct ...

Choose the default text option for your AngularJS dropdown menu

I am facing an issue with my angularjs dropdownlist that is using ng-options. <select ng-options="perlocation.name for perlocation in locations" ng-model="locationDropdown"> Even though my dropdown list loads correctly, the selected option 0 is dis ...

Can you explain the contrast between using require('d3') and require('d3-selection')?

While working on a nodejs application with javascript, I encountered an interesting issue. In my code, I am passing a d3 selection to a function as shown below. // mymodule.js exports.myfunc = function(ele){ if(ele instanceof d3.selection){ // do so ...

The labels for my Angular Material form within the dialogue are not visible and the styling appears incorrect until I begin inputting information

https://i.sstatic.net/njp4A.png Upon opening the dialogue, I noticed that only the phone number, email, name, and location fields were properly styled, while the others were not and the labels weren't displaying. Prior to adding appearence="out ...

Is it possible to determine the size of an array using the eval() function?

How come this is not functioning as expected? var issue_0 = ["a","b","c","d"]; arrayname = "issue_0"; arraylength = eval([arrayname]).length; for (i = 0; i < arraylength; i++) { I'm attempting to access different arrays based on user input, so I ...

Converting an array of strings to integers using Highcharts and JavaScript

Trying to create a chart using highcharts involves getting data from a datatable in VB.NET, converting it into an array, then transforming it into JSON before passing it back to JavaScript for rendering. However, the data is not appearing on the chart, pos ...

Is there a way to achieve a XNOR-like response with necessary input?

I'm currently working with a form that looks like this: <form> <input type="text" name="input1"> <input type="text" name="input2"> <button type="submit"> ...

Expanding superagent functionality through proxy integration

I am facing an issue where I cannot find any TypeScript definitions for the module superagent-proxy. This leads to errors when compiling my TypeScript application to JavaScript, specifically: ts: Property 'proxy' does not exist on type 'S ...

Can a correctly typed text alter the image?

I am working on a feature where the image changes when the user enters the correct text, indicating that it was typed correctly. However, I am facing an issue where if the first two characters are entered correctly but the third one is not, the image still ...

nginx error when trying to navigate angular routes

My Angular app is hosted in GKE using nginx with the following configuration: location / { root /usr/share/nginx/www; try_files $uri $uri/ /index.html } When I access http://ipaddress/field, it loads the application at http://ipaddress ...

Is there a way for me to make my image source dynamically switch between 3-4 different images when hovered over?

I'm in the midst of a college project where I'm designing a clothing website. What I'm aiming for is to have the product image on the main feed change between 3-4 images of the same product with a quick transition when a user hovers over it. ...

Restrict the number of labels on Chart.js exclusively for smaller displays

How to Limit the Number of Labels on a Chart.js Line Chart I am looking for a way to decrease the number of labels on my line chart only when it is viewed on a small device. The solution provided in the previous post suggests using the following code: xAx ...

What could be causing express to have trouble finding the ejs file in the views directory?

Recently delved into the world of learning NodeJS and Express. // Working with express framework var express = require("express"); var app = express(); app.get("/", (req,res) => { res.render("home.ejs"); }) //Setting up port listening app.listen ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...

Ways to eliminate the occurrence of 'undefined' in Object.keys while using forEach loop

Hey there! I'm currently working with Node.js and running into an issue with using forEach on Object.keys. In the code snippet below, when I try to execute it, I encounter a problem where the first value in the output is undefined. For instance, let&a ...

"Troubleshooting the issue of nested jQuery Ajax requests failing to execute properly

UPDATE: I'm getting an error saying that my li tag is considered an illegal token. I'm unsure how to resolve this issue as I believed I was appending it within a ul tag I'm tasked with fetching a JSON array of public Github repositories and ...

The initial loading of jQuery DataTables shows duplicate entries

Expanding on my query from the previous day: jQuery AJAX call function on timeout Following the guidance provided in the response from yesterday's post, the table successfully reloads without requiring a full page refresh every 30 seconds. However, ...

Error: TypeScript encountered an issue while attempting to access a property that is undefined

I just can't seem to figure out what's missing here. Running the following code gives me this error: Uncaught TypeError: Cannot read property 'addEventListener' of undefined" class Editor{ public co ...

Transferring Data from Extension to Webpage for the First Page Load - Firefox

Developing an extension for browsers like Chrome and Firefox. As per our requirements, we need to transfer some stored information from the extension to the webpage during page load. This data should be available on the webpage before any XHR request is tr ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...