猿问

Angular 8:Reactive Form Automap 数据

有没有一种简单的方法可以使用自动映射器修补 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;”类型的参数 }'


一只甜甜圈
浏览 116回答 2
2回答

慕后森

如果表单模型和数据想要补丁对象具有相同的值,那么试试这个。this.editAddressForm.patchValue(this.addressMailingData);

萧十郎

更多定制:customPatchValue(keys : string[], data: any, 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
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答