2 回答

TA貢獻1802條經驗 獲得超5個贊
如果表單模型和數據想要補丁對象具有相同的值,那么試試這個。
this.editAddressForm.patchValue(this.addressMailingData);

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;
}
}
添加回答
舉報