如何更新FormArray控件 [英] How to update controls of FormArray

查看:68
本文介绍了如何更新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');

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

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

setValue需要一个与整个结构或FormArray匹配的数组,而patchValue可以采用该数组的超集或子集. ( FormArray类)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆