Setting Angular 2 FormArray value in ReactiveForm?

心不动则不痛 提交于 2019-12-05 03:36:47

To set the values and remove the values from the FORM array refer below code. this is a general example. please adjust to your code

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

I am having the same issue. Here is how I do it:

As you mentioned, you initialize your form Array like this:

  addresses: this._fb.array([])

Then inside ngOnInit() (or in my case ionViewDidLoad() - using Ionic 2), you do your async operation to hit your remote database and get back the value either via promise or observable (and subscribe to the observable). Then you patchValue to all the other form control that is NOT formArray (don't use setValue if you have form group and form array!!).

For the formArray, do this:

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

Where data.addresses is an array of addresses (you create them from the same form on previous operation.)

Hope this solve your question as well as mine :) FormArray is powerful, wish there is more resources to teach us how to use it correctly.

This is a working code. You can insert it into the project and test it.

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 || []));

  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!