2016-08-30 31 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);