Angular 8:响应式表单自动映射和PatchValue Set成员数据

时间:2019-11-11 03:36:38

标签: javascript css angular typescript angular8

是否有使用自动映射器修补Angular表单的简便方法?我想上一堂课,并将完全相同的成员姓名放入表格中。我宁愿不写,因为公司形式繁多,并尽量避免重复编码(干式原则)等

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

尝试的解决方案:这样做会导致以下错误

this.editAddressForm.patchValue(this.addressMailingData);
  

错误:类型'string'的参数不能分配给类型'{[key:string]:any; }'

2 个答案:

答案 0 :(得分:1)

如果表单模型和数据希望补丁对象具有相同的值,请尝试执行此操作。

this.editAddressForm.patchValue(this.addressMailingData);

答案 1 :(得分:1)

更多定制:

  

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

     

参数:

  • 键:您要将值映射到字符串的字符串数组 表单组
  • 数据:具有您要为formGroup设置的值的对象
  • formGroup:您要对其应用更改的Formgroup
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);
    }
  });
}

这是TS代码:

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