Amg*_*rry 70 angular2-forms angular
所以我有一个复杂的形式来创建一个实体,我想用它来编辑我也使用新的角形式API.我将表单的结构与从数据库中检索的数据完全相同,因此我想将整个表单的值设置为此处检索的数据,这是我想要做的示例:
this.form = builder.group({
b : [ "", Validators.required ],
c : [ "", Validators.required ],
d : [ "" ],
e : [ [] ],
f : [ "" ]
});
this.form.value({b:"data",c:"data",d:"data",e:["data1","data2"],f:data});
Run Code Online (Sandbox Code Playgroud)
PS:NgModel不能用于新的表单api我也不介意在模板中使用单向数据绑定
<input formControlName="d" value="[data.d]" />
Run Code Online (Sandbox Code Playgroud)
这有效,但在数组的情况下会很痛苦
Ste*_*aul 223
要设置所有 FormGroup值,请使用setValue:
this.myFormGroup.setValue({
formControlName1: myValue1,
formControlName2: myValue2
});
Run Code Online (Sandbox Code Playgroud)
要仅设置某些值,请使用patchValue:
this.myFormGroup.patchValue({
formControlName1: myValue1,
// formControlName2: myValue2 (can be omitted)
});
Run Code Online (Sandbox Code Playgroud)
使用第二种技术,不需要提供所有值,并且不会设置未设置值的字段.
Var*_*ork 14
您可以使用 form.get 获取具体的控件对象并使用 setValue
this.form.get(<formControlName>).setValue(<newValue>);
Run Code Online (Sandbox Code Playgroud)
小智 7
对于您的控件是FormGroup的设置值,可以使用此示例
this.clientForm.controls['location'].setValue({
latitude: position.coords.latitude,
longitude: position.coords.longitude
});
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用 setValue 为编辑/更新目的设置值。
this.personalform.setValue({
name: items.name,
address: {
city: items.address.city,
country: items.address.country
}
});
Run Code Online (Sandbox Code Playgroud)
您可以参考http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/了解如何通过 setValue 使用 Reactive 表单进行添加/编辑功能。它节省了我的时间