Angular2 为 formGroup 设置值 [英] Angular2 set value for formGroup

查看:45
本文介绍了Angular2 为 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.

这篇关于Angular2 为 formGroup 设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆