如何更新FormArray控件 [英] How to update controls of FormArray
问题描述
我的表单组代码为
this.myForm = this._fb.group({
branch_name: ['', [Validators.required]],
branch_timing: this._fb.array([
this.initBranchTiming(),
])
});
initBranchTiming() {
return this._fb.group({
day: ['', []],
open_from: ['00:00:00', []],
open_till: ['00:00:00', []]
});
}
branch_name通过此代码更新
(<FormControl>this.myForm.controls['branch_name']).updateValue(this.branch_detail.branch_name);
现在我必须更新表单数组的'day'字段.如何更新表单数组branch_timing的'day'字段?
AFAIK将FormGroup
放在FormArray
内会剥离其名称的"FormControls",并使其像普通数组一样只是一个列表./p>
为了分别更新FormControls
,请使用索引从FormGroup
更新每个AbstractControl
的值:
let index = 0; // or 1 or 2
(<FormArray>this.myForm.controls['branch_timing']).at(index).patchValue('example');
或者您可以通过调用setValue
或patchValue
来更新整个FormArray
:
(<FormArray>this.myForm.controls['branch_timing']).setValue(['example', 'example1', 'example2']);
setValue
需要一个与整个结构或FormArray
匹配的数组,而patchValue
可以采用该数组的超集或子集. (
My form group code is as
this.myForm = this._fb.group({
branch_name: ['', [Validators.required]],
branch_timing: this._fb.array([
this.initBranchTiming(),
])
});
initBranchTiming() {
return this._fb.group({
day: ['', []],
open_from: ['00:00:00', []],
open_till: ['00:00:00', []]
});
}
branch_name is updated by this code
(<FormControl>this.myForm.controls['branch_name']).updateValue(this.branch_detail.branch_name);
Now i have to update the 'day' field of form array. what to do to update the 'day' field of form array branch_timing ?
AFAIK putting a FormGroup
inside of a FormArray
strips the 'FormControls' of their names and makes it just a list, like a normal array.
In order to update the FormControls
individually, you update the value of each AbstractControl
from the FormGroup
by using the index:
let index = 0; // or 1 or 2
(<FormArray>this.myForm.controls['branch_timing']).at(index).patchValue('example');
Or you can update the entire FormArray
by calling setValue
or patchValue
:
(<FormArray>this.myForm.controls['branch_timing']).setValue(['example', 'example1', 'example2']);
setValue
requires an array that matches the entire structure or the FormArray
, while patchValue
can take a super-set or sub-set of the array. (FormArray-class on Angular2's website)
这篇关于如何更新FormArray控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!