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

查看:27
本文介绍了如何更新 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 被此代码更新

branch_name is updated by this code

(<FormControl>this.myForm.controls['branch_name']).updateValue(this.branch_detail.branch_name);

现在我必须更新表单数组的天"字段.如何更新表单数组 branch_timing 的 'day' 字段?

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 将 FormGroup 放在 FormArray 中,去掉它们名称中的FormControls"并使其成为只是一个列表,就像一个普通的数组.

AFAIK putting a FormGroup inside of a FormArray strips the 'FormControls' of their names and makes it just a list, like a normal array.

为了单独更新 FormControls,您可以使用索引从 FormGroup 更新每个 AbstractControl 的值:

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');

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

Or you can update the entire FormArray by calling setValue or patchValue:

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

setValue 需要一个与整个结构或 FormArray 匹配的数组,而 patchValue 可以采用数组.(Angular2 网站上的 FormArray-class)

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天全站免登陆