在 ReactiveForm 中设置 Angular 2 FormArray 值? [英] Setting Angular 2 FormArray value in ReactiveForm?

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

问题描述

这里已经有一个类似的问题(设置初始值Angular 2反应式formarray) 但我对答案不满意,或者可能正在寻找其他解决方案.

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 的全部意义在于传递对象数组,它应该创建相同数量的组件.但是在上面的示例中,如果您查看提供的 plunker ,即使在提供了两个 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('yourEmailId@gmail.com');
        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 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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