formGroup的Angular2设置值 [英] Angular2 set value for formGroup
问题描述
因此,我有一个用于创建实体的复杂表格,我也想将其用于编辑,我正在使用新的角度表格API.我完全按照从数据库中检索到的数据来结构化表单,因此我想将整个表单的值设置为所检索到的数据,这是我要执行的操作的一个示例:
So I have a complex form for creating an entity and I want to use it for editing as well I am using new angular forms API. I structured the form exactly as the data I retrieve from the database so I want to set the value of the whole form to the data retrieved here is an example to what i want to do:
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});
PS:NgModel不适用于新表格api,我也不介意在模板中使用一种方式进行数据绑定,如
PS: NgModel doesn't work with new forms api also i don't mind using one way data binding in template as in
<input formControlName="d" value="[data.d]" />
可行,但如果要使用数组,那会很痛苦
that works but it would be a pain in case of the arrays
推荐答案
要设置所有 FormGroup值,请使用 setValue :
To set all FormGroup values use, setValue:
this.myFormGroup.setValue({
formControlName1: myValue1,
formControlName2: myValue2
});
要仅设置一些值,请使用 patchValue :
this.myFormGroup.patchValue({
formControlName1: myValue1,
// formControlName2: myValue2 (can be omitted)
});
使用第二种方法,不需要提供所有值,并且未设置其值的字段不会受到影响.
With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.
这篇关于formGroup的Angular2设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!