简体   繁体   中英

Angular 8: Reactive Form Automap and PatchValue Set Member data

Is there an easy way to patch an Angular form with auto mapper? I Want to take a class, and place the exact same member names into the form. I prefer not to write as company has many forms, and trying to stay away from repetitive coding (dry principle), 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

Attempted Solution: Doing this results in error below

this.editAddressForm.patchValue(this.addressMailingData);

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

if form model and data want patch object having same values then try this.

this.editAddressForm.patchValue(this.addressMailingData);

Bit more customize:

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

Pararmeters:

  • keys: An array of string which you want to map the values to the formgroup
  • data: Object that has values which you want to set for the formGroup
  • formGroup: Formgroup for which you want to apply the changes
customPatchValue(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);
    }
  });
}

Here is TS 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: "Prashant", surname: "Pimpale" };

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

  customPatchValue(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;
  }
}

A Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM