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