Is it It looks like Angular2\'s FormGroup.patchValue() doesn\'t push new elements into an array.
For example something like this:
ngOnInit() {
Well, the solution I found out is:
this.myForm.controls['array'] = this.formBuilder.array(newArray.map(i => this.formBuilder.group(i)));
Well, as silentsod said, it is not possible. Currently, I am using below as an alternative:
let controlArray = <FormArray>this.form.controls['apps'];
this.list.forEach(app => {
const fb = this.buildGroup();
fb.patchValue(app);
controlArray.push(fb);
});
Angular Team - We need a new function something like PatchArray() that would patch from a collection/object graph. It is a basic use case.
.patchValue()
only updates the existing FormArray
, it won't modify the structure of your form model.
patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.
It accepts both super-sets and sub-sets of the array without throwing an error.
You actually need to push a new element onto the array in order for it to appear.
this.form.controls['students'].push(new FormControl('This will not show'));
This is all in the FormArray
documentation https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html
I hope this will help you. I have a complex object where my object has an object inside and object inside. sorry for my grammar. but i hope my code will help you
ngOnInit() {
this.descriptifForm = this._fb.group({
name: 'ad',
descriptifs: this._fb.array([ this.buildForm() ]),
});
this._service.getData().subscribe(res => {
this.descriptifForm.setControl('descriptifs', this._fb.array(res || []));
});
}
buildA(): FormGroup {
return this._fb.group({
Id: '',
Groups: this._fb.array([ this.buildB() ]),
Title: ''
});
}
buildB(): FormGroup {
return this._fb.group({
Id: '',
Fields: this._fb.array([ this.bbuildC() ]),
Type: ''
});
}
buildC(): FormGroup {
return this._fb.group({
Answers: this._fb.array([ this.buildD() ]),
Code: '',
});
}
buildD(): FormGroup {
return this._fb.group({
Data: ''
});
}