Discover the power of Angular 8: Automatically mapping member data with Reactive Form Automap and efficiently setting values

Is there a simple method to patch an Angular form using auto mapper? I am looking to transfer member names from a class directly into the form without having to manually write out each one. This is especially important as my company has many forms and I want to follow the DRY principle to avoid repetitive coding, etc.

this.editAddressForm.patchValue({
     'streetNumber':  this.addressMailingData.streetNumber,
     'predirectional':  this.addressMailingData.predirectional,
     'streetName':  this.addressMailingData.streetName,
     'streetType':  this.addressMailingData.streetType,
     'postdirectional':  this.addressMailingData.postdirectional,
     'city': this.addressMailingData.city,
     'state': this.addressMailingData.state,
     'postalCode':  this.addressMailingData.postalCode

Possible Solution: When attempting to do this by simply passing in the entire addressMailingData object like below, an error occurs:

this.editAddressForm.patchValue(this.addressMailingData);

Error: Argument of type 'string' is not assignable to parameter of type '{ [key: string]: any; }'

Answer №1

For updating an object with matching values in form model and data, use the following code snippet:

this.updateObjectForm.patchValue(this.objectData);

Answer №2

Adding a touch of personalization:

applyCustomChanges(keys : string[], data: any, formgroup: FormGroup):

Parameters:

  • keys: A collection of strings to be mapped to the formgroup
  • data: Object containing values to be set for the formGroup
  • formGroup: The specific Formgroup where changes will be applied
applyCustomChanges(keys: string[] = null, data: any, formGroup: FormGroup) {
  Object.keys(data).forEach(key => {
    if (!keys || keys.length == 0 || keys.some(x => x == key)) {
      formGroup.patchValue({ [key]: data[key] })
    } else {
      console.log("Non matching key", key);
    }
  });
}

Snippet of TypeScript Code:

import { Component } from "@angular/core";
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  form: FormGroup;

  obj: any = { name: "John", surname: "Doe" };

  constructor() {
    this.form = new FormGroup({
      name: new FormControl(""),
      surname: new FormControl("")
    });
    
    this.applyCustomChanges(['name'], this.obj, this.form);
  }

  applyCustomChanges(keys: string[] = null, data: any, formGroup: FormGroup) {
    Object.keys(data).forEach(key => {
      if (!keys || keys.length == 0 || keys.some(x => x == key)) {
        formGroup.patchValue({ [key]: data[key] })
      } else {
        console.log("Non matching keys", key);
      }
    });
    return formGroup;
  }
}

See Demo Here

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 creating a tab logo?

Is there a way to create a personalized logo to appear next to the website title on the tab? Whenever I see a logo displayed beside the website title in my browser tabs, I can't help but wonder how it's done. ...

What is the method for making an interface extension from a type as optional?

Can you help me create an interface that includes all students and part of a school, ensuring that gender is required for Peter and optional for other students? export type School = { address: string; state: string; }; export type Gender = { gender: ...

Encountering a 415 Error while making an ajax call using formData

I am attempting to make an ajax call with formData that includes a list of image files and some strings. However, the call is not successful and I am receiving error 415. Here is the code: var file = picChooser.files[0]; var jobExecutionImagesContext = n ...

What is the best way to evaluate the rows of two specific elements?

My validation process involves comparing individual rows in the clientDocument with the corresponding rows in the serverDocument, instead of comparing the entire documents at once. Currently, I am using the following code snippet for comparison: JSON.stri ...

Executing a webservice method in an html page using javascript without the need to refresh the page

Is it possible to call a webservice from an index.html page using JavaScript? My webservice is located at "localhost/ws/service.asmx" and the specific web method I want to call is called HelloWorld. The index.html page contains an HTML submit button whic ...

"Despite being on a right-to-left page, Mat-icon still adheres to rules for left-to

Currently, I am working on enhancing the right-to-left language support for my Angular v11 application that utilizes Material for styling. One of the challenges I faced was ensuring that all elements, including mat-icons, follow the correct directionality ...

To display the elements of an array in a dropdown menu

I have a collection of arrays within an object. {"ItemIsExportControlled":["true","false"],"OrderShippingDestination":["domestic","foreign"],"OrderShipping":["ground","air","sea"],"ItemStockStatus":["validInStock","invalid","validOutOfStock"],"OrderDelive ...

The TypeScript factory class anticipates an intersection

In my code, I have a class factory called pickSomething that generates a specific type based on a key provided from a ClassMap: class A { keya = "a" as const; } class B { keyb = "b" as const; } type ClassMap = { a: A b: B } c ...

I have implemented a button in PHP and now I am looking to invoke a function when that button is clicked

I have a PHP-generated HTML button and I'm having trouble calling the mybtn3() function when it is clicked. The button code looks like this: echo"<td width=14% align=center><input type=button value=Export onclick=mybtn3() /></td>"; ...

PHP is encountering issues when attempting to dynamically add rows using JavaScript

I have created this HTML code to dynamically generate rows: <tr > <td><?php echo $row['qty'];?></td> <td class="record"><?php echo $row['prod_name'];?></td> <td><input type ...

Establish the condition if the array is present

I am looking to conditionally set a state based on the existence of data retrieved from the server. const [names, setNames] = useState([...details?.names]) The details object is passed in as props and fetched from the database. The array details.names com ...

`Advancing Angular Bootstrap popover placement in response to varying circumstances`

As a complete novice in the world of Angular, I've done my fair share of research but still can't seem to find what I'm looking for. Here's a snippet of code that I'm working with: @Component({ selector: "help-icon", templateUrl: ...

Issue with floating right navigation functionality

Hi there, I'm experiencing a minor issue with the navigation on my website. When I hover over the right side of the nav bar, the drop down menu shifts slightly to the right. All other elements in the nav are positioned absolutely... nav { pa ...

Is there a way to implement seamless scrolling within an absolute element using Jquery?

Hey there! I recently implemented smooth scrolling on my website, but it seems to only work on single-page layouts. How can I make it function properly within an absolutely positioned scrollable element? Here are the link to my website and the correspond ...

Angular: Effective communication between components through routing and Observable binding ultimately results in the advancement of ngtsc(233

I designed an Angular Component named "crear-pedido" that exhibits a catalog of items (using row of products) and my aim is for the user to have the ability to click on the values in the ID column and navigate the application to a subordinate component kno ...

Tips for comparing array objects in two separate React states

Comparing object arrays in two different React states can be challenging. Here is an example of the state values: review1 = [{name: John, Title: Manager},{name: Peter, Title: Engineer}, {name: Serena, Title: Supervisor}] review2 = [{personName: John, isma ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

Is there a native feature in Vue.js that allows for the addition of a duplicate of a constantly saved object to an array that is repeated

Having an issue with my Vue.js app where adding a newItem to a list of items results in the added object being bound to the input. Here's what I've tried so far: new Vue({ el: '#demo', data: { items: [ { start: & ...

Image-switching button

I'm new to JavaScript and struggling with my first code. I've been staring at it for two days now, but can't figure out what's wrong. The goal is to create an HTML page where the user can change an image by clicking on a button, and th ...

Encountering an abrupt conclusion in JSON input while utilizing cucumber-html-reporter alongside Nightwatch-Cucumber

I have been utilizing Nightwatch-Cucumber to automate my end-to-end tests and I am encountering an issue when trying to generate a cucumber html report after test execution using cucumber-html-reporter. The error message I receive during the report generat ...