gpt4 book ai didi

Angular2 为 formGroup 设置值

转载 作者:太空狗 更新时间:2023-10-29 16:46:11 25 4
gpt4 key购买 nike

所以我有一个用于创建实体的复杂表单,我也想使用它进行编辑,我正在使用新的 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});

PS:NgModel 不适用于新的表单 api,我也不介意在模板中使用一种数据绑定(bind)方式,如

<input formControlName="d" value="[data.d]" />

这行得通,但在数组的情况下会很痛苦

最佳答案

要设置所有 FormGroup 值,请使用setValue:

this.myFormGroup.setValue({
formControlName1: myValue1,
formControlName2: myValue2
});

要设置仅一些值,使用patchValue:

this.myFormGroup.patchValue({
formControlName1: myValue1,
// formControlName2: myValue2 (can be omitted)
});

使用第二种技术,不需要提供所有值,并且未设置值的字段不会受到影响。

关于Angular2 为 formGroup 设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38655613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com