How to update controls of FormArray

北城余情 提交于 2019-12-08 14:46:12

问题


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 ?


回答1:


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)




回答2:


This is tested and works on Angular 2.0.0-rc.4 with @angular/forms 0.2.0:

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

In the release version, Angular 2.0.0 with @angular/forms 2.0.0, the syntax has been simplified:

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

and

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



回答3:


You can do this simply by creating a new FormControl :

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

Or by removing all items before updating them :

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



回答4:


Try it, hope it will work for you:

 this.myForm.controls.splice(0);


来源:https://stackoverflow.com/questions/39229398/how-to-update-controls-of-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!