[英]Angular 8: Reactive Form Automap and PatchValue Set Member data
有沒有一種簡單的方法可以使用自動映射器修補 Angular 表單? 我想要一個 class,並將完全相同的成員名稱放入表格中。 我不想寫,因為公司有很多 forms,並試圖遠離重復編碼(干原則)等
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; 類型的參數 }'
如果表格 model 和數據希望補丁 object 具有相同的值,那么試試這個。
this.editAddressForm.patchValue(this.addressMailingData);
更多自定義:
customPatchValue(keys: string[], data: any, 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.