Angular2: Cannot find form control at index 1 at FormArray
The mentioned error is caused by calling this.serviceFrm.setValue(resp)
(https://github.com/angular/angular/blob/master/packages/forms/src/model.ts#L1382).
This method performs strict checks, so it will throw an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control.
You are trying to assign an array of 3 items (according to your snapshot) to FormArray having only one initial FormGroup at index 0, so assigning value at index 1 fails, as it does not exist.
To solve it empty your form array before patching value, use patchValue()
(which accepts partial value) instead of setValue()
and then push each value in a loop:
getService(): void {
const id = parseInt(this._route.snapshot.params['id']);
if (id && id > 0) {
this.indLoading = true;
this._restService.getById('/api/serviceapi/', id).subscribe(
resp => {
// get form array reference
const staffs = this.serviceFrm.get('Staffs') as FormArray;
// empty form array
while (staffs.length) {
staffs.removeAt(0);
}
// use patchValue instead of setValue
this.serviceFrm.patchValue(resp);
// add form array values in a loop
resp.Staffs.forEach(staff => staffs.push(this.fb.group(staff));
},
error => this.msg = <any>error
);
}
}
It is possible to use setControl
with FormArrays. The code below is an example from Deborah Kurata:
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});
...
// Update the data on the form
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode,
starRating: this.product.starRating,
description: this.product.description
});
// This line makes the array update!
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));