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;
}
}
添加回答
举报