亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular 8:Reactive Form Automap 數據

Angular 8:Reactive Form Automap 數據

一只甜甜圈 2021-12-23 14:32:56
有沒有一種簡單的方法可以使用自動映射器修補 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 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

如果表單模型和數據想要補丁對象具有相同的值,那么試試這個。

this.editAddressForm.patchValue(this.addressMailingData);


查看完整回答
反對 回復 2021-12-23
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

更多定制:

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


查看完整回答
反對 回復 2021-12-23
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號