本文介绍了在ReactiveForm中设置Angular 2 FormArray值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处已经存在类似的问题(设置初始值Angular 2反应式数组),但我对答案不满意,或者正在寻找其他解决方案.

There is already a similar question here (Setting initial value Angular 2 reactive formarray) but I am not satisfied with the answer or maybe looking for some other solution.

我认为拥有FormArray的全部目的是传递对象数组,并且它应该创建相等数量的组件.但是在上面的示例中,即使提供了两个Addresses对象,如果您查看了所提供的插件,便创建了一个Address,因为已经在ngOnInit()中创建了其空白版本.

I think whole point of having FormArray is to pass the array of objects and it should create equal number of components. But in this above example if you look at the provided plunker , even after providing two Addresses object one Address was created because its blank version was already created in ngOnInit() .

所以我的问题是,在ngOnInit()中是否有这样的地址:this._fb.array([])//空白列表,那么我应该如何设置它的值,以使其从TypeScript数组中的N个地址中动态创建N个地址?

So my question is if in ngOnInit() I have it like this addresses: this._fb.array([]) // blank list,then how should I set its value that it dynamically creates N number of addresses from N number of addresses in my TypeScript array ?

推荐答案

要设置和删除 表单数组 中的值,请参考以下代码.给出的代码仅供参考,请相应地调整代码.

To set and remove the values from the form array refer to the below code. The given code is just for your reference, please adjust to your code accordingly.

import { FormArray, FormBuilder, FormGroup} from '@angular/forms';

export class SomeComponent implements OnInit {

consutructor(public  fb:FormBuilder) { }

    ngOnInit() {
      public settingsForm: FormGroup = this.fb.group({
          collaborators:this.fb.array([this.buildCollaboratorsGroup(this.fb)])
      });

      this.setFormArrayValue();
   }

    public buildCollaboratorsGroup(fb:FormBuilder): FormGroup {
        return fb.group({
                           email:'',
                           role:''
                       });
    }


    // Here I'm setting only one value if it's multiple use foreach
    public setFormArrayValue() {
        const controlArray = <FormArray> this.settingsForm.get('collaborators');
        controlArray.controls[0].get('email').setValue('[email protected]');
        controlArray.controls[0].get('role').setValue(2);
    }

    // Here removing only one value if it's multiple use foreach
    public removeFormArrayValue() {
        const controlArray = <FormArray> this.settingsForm.get('collaborators');
        controlArray.removeAt(0);
    }
}

这篇关于在ReactiveForm中设置Angular 2 FormArray值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:23