2016-08-30 33 views
10

我的表单组代码控制是如何更新的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); 

现在我有更新的形式排列的“天”字段更新。如何更新表单数组branch_timing的'day'字段?

回答

-1

没有测试,但我想这应该做你想要什么:

this.myForm.get('branch_name.0.day') 
.setValue(this.branch_detail.branch_name); 
+0

我得到此构建错误- 属性'getControl'不存在类型'FormGroup'上。 – Mubashir

+0

你使用的是什么Angular2版本? AFAIR最近改变了,之前命名为find()。 –

+0

我正在使用RC4版本和窗体是 “@ angular/forms”:“^ 0.2.0”, – Mubashir

0

这是测试,并在角2.0.0 rc.4可与@角/ 0.2.0形成:

(<FormControl>this.myForm.controls.branch_timing.controls[0].controls.day) 
    .updateValue('new value'); 

在发行版本,角2.0.0与@角/形成2.0.0,语法已被简化:

this.myForm.value.branch_name = this.branch_detail.branch_name; 

this.myForm.value.branch_timing[0].day = 'New Value'; 
4

AFAIK把一个FormGroup一个FormArray内剥去他们的名字“FormControls”,使它只是一个列表,像一个正常的阵列。

为了更新FormControls独立,您可以通过使用索引更新每个AbstractControlFormGroup值:

let index = 0; // or 1 or 2 
(<FormArray>this.myForm.controls['branch_timing']).at(index).patchValue('example'); 

或者您也可以通过调用setValuepatchValue更新整个FormArray

(<FormArray>this.myForm.controls['branch_timing']).setValue(['example', 'example1', 'example2']); 

setValue需要一个匹配整个结构或FormArray的数组,而patchValue ca n取数组的超集或子集。 (FormArray-class on Angular2's website

+2

@Frederico P最好的建议在网上找到添加到formArray!不过,我需要这个工作:'( this.formName.get('FormArrayName'))。push(new FormControl('SOME VALUE'));' – BenRacicot

+0

如果您想要替换当天,我这样做:( this.myForm.controls ['branch_timing'])。at(index).get(“day”)。setValue(“222”); – Samuel

-2

尝试它,希望它会为你工作:

this.form.setControl('items', new FormControl(arrayItemsValue)); 

或者通过:

this.myForm.controls.splice(0);

+0

对不起,这是错误的 –

+0

你应该可以删除它。在您的答案下搜索“删除”链接 –

0

你可以简单地通过创建一个新FormControl做到这一点更新它们之前删除所有项目:

const items = (<FormArray>this.form.get('items')); 
for (let i = 0; i < items.length; i++) { 
    items.removeAt(i); 
} 
this.form.get('items').setValue(arrayItemsValue);