Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Angular 2 FormArray value in ReactiveForm?

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.

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() .

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 ?

like image 813
Dany Avatar asked Jan 18 '17 18:01

Dany


People also ask

How do you set a value on FormArray?

FormArray setValue() setValue() sets the value of the FormArray . We need to pass an array that matches the structure of the control. Create a sample FormArray . myFormArray = new FormArray([ new FormControl(), new FormControl(), new FormControl() ]);

How do you set value in reactive form?

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances. patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls.

How to use formarray in angular forms?

To use FormArray, First, you need to import the FormArray from the Angular Forms Module. Build a form model skillsForm using the FormBuilder. Our Form has two fields. name of the person and his skills.

How do I programmatically create a form in angular reactive forms?

In Angular Reactive Forms, every form has a form model defined programmatically using the FormControl and FormGroup APIs, or alternatively using the more concise FormBuilder API, which we will be using throughout this guide.

What is form array in angular?

Angular FormArray is an inbuilt class that tracks the value and validity state of an array of FormControl, FormGroup, or FormArray instances. For example, if one of the controls in a FormArray is invalid, an entire array becomes invalid. Angular FormArray is one of the three fundamental building blocks used to define forms in Angular, ...

How to dynamically add controls to an array in angular forms?

While in FormArray, the controls become part of an array Because it is implemented as an Array, it makes it easier dynamically add controls. Let us build a simple app, which allows us to add the new skill of a person dynamically. To use FormArray, First, you need to import the FormArray from the Angular Forms Module.


3 Answers

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);        
    }
}
like image 98
Praveen M P Avatar answered Oct 06 '22 05:10

Praveen M P


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.

like image 26
Hugh Hou Avatar answered Oct 06 '22 04:10

Hugh Hou


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 protected]'
      },
      '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 || []));

  }
}
like image 34
Victor Isaikin Avatar answered Oct 06 '22 06:10

Victor Isaikin