在ReactiveForm中设置Angular 2 FormArray值?

时间:2017-01-18 18:38:10

标签: javascript forms angular

这里已经存在类似的问题(Setting initial value Angular 2 reactive formarray),但我对答案不满意或者可能正在寻找其他解决方案。

我认为使用FormArray的重点是传递对象数组,它应该创建相同数量的组件。但是在上面的示例中,如果查看提供的plunker,即使提供了两个Addresses对象,也会创建一个Address,因为它的空白版本已经在ngOnInit()中创建。

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

3 个答案:

答案 0 :(得分:4)

我遇到了同样的问题。我是这样做的:

正如您所提到的,您可以像这样初始化表单数组:

  addresses: this._fb.array([])

然后在ngOnInit()(或者在我的情况下是ionViewDidLoad() - 使用Ionic 2)中,执行异步操作以命中远程数据库并通过promise或observable(并订阅observable)获取值。然后你patchValue到所有其他非formArray的表单控件(如果你有表单组和表单数组,请不要使用setValue !!)。

对于formArray,请执行以下操作:

   this.yourForm.setControl('addresses', this.fb.array(data.addresses || []));

其中data.addresses是一个地址数组(您可以在之前的操作中使用相同的表单创建它们。)

希望这能解决你的问题以及我的问题:) FormArray很强大,希望有更多的资源来教我们如何正确使用它。

答案 1 :(得分:4)

要设置值并从FORM数组中删除值,请参阅下面的代码。这是一个普遍的例子。请调整您的代码

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

export class SomeComponent implements OnInit {

consutructor(public  fb:FormBuilder) { }

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

    ngOnInit() {

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

      this.setFormArrayValue();
   }


    // 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);        
    }
}

答案 2 :(得分:1)

这是一个有效的代码。你可以将其插入到该项目,并对其进行测试。

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private addresses: string[] = ['Address 1', 'Address 2', 'Address 3'];
  private form: FormGroup;

  constructor(private formBuilder: FormBuilder){}

  ngOnInit(){
    // Init Form
    this.form = new FormGroup({
      'userData': new FormGroup({
        'username': new FormControl(null, [Validators.required]),
        'email': new FormControl(null, [Validators.required, Validators.email])
      }),
      'addresses': new FormArray([])
    });

    // If you want to insert static data in the form. You can use this block.
    this.form.setValue({
      'userData': {
        'username': 'Vic',
        'email': 'email@email.com'
      },
      'addresses': [] // But the address array must be empty.
    });

    // And if you need to insert into the form a lot of addresses. 
    // For example, which belong to one user and so on. 
    // You must use this block. 
    // Go through the array with addresses and insert them into the form.
    this.addresses.forEach((value) => {
      const control = new FormControl(value, Validators.required);
      (<FormArray>this.form.get('addresses')).push(control);
    });
    // Or you can use more better approach. But don't forget to initialize FormBuilder.
    this.form.setControl('addresses', this.formBuilder.array(this.addresses || []));

  }
}