是否有使用自动映射器修补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; }'
答案 0 :(得分:1)
如果表单模型和数据希望补丁对象具有相同的值,请尝试执行此操作。
this.editAddressForm.patchValue(this.addressMailingData);
答案 1 :(得分:1)
更多定制:
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;
}
}