问题
I have a reactive form that on cancel
has to set again the initial form values into the formGroup.
import { Map } from "immutable";
@Input() data: any;
public ngOnInit() {
if (this.data && this.data.controls) {
this.group = this.fb.group({
isActive: [this.data.isActive],
items: this.fb.array(this.buildFormArray(this.data.controlPerformers)),
});
// Deep copy of the formGroup with ImmutableJs
this.originalFormData = Map(this.group).toJS();
}
}
public buildFormArray(controllers: IControlPerformer[]) {
return controllers.map((ctlr) => {
return this.fb.group({
user: [ctrl.userData],
ctrlName: [ctlr.name, Validators.required],
date: [moment(ctlr.date).toDate(), Validators.required],
});
});
}
public cancel() {
const existingItems = this.group.get("items") as FormArray;
while (existingItems.length) {
existingItems.removeAt(0);
}
// Here the error when trying to set the FormArray value
this.group.setValue(this.originalFormData.value);
}
The error message:
There are no form controls registered with this array yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout).
This question had the same issue, but I could not fix it in my case.
UPDATE - Below The value of formGroup
. It looks good and properly initialized.
{
"isActive": true,
"items": [
{
"user": "Walter",
"ctrlName": "Orders",
"date": "2018-03-18T23:00:00.000Z"
}
}
回答1:
If you remove items from the form array, then you need to add them anew, since setValue
or patchValue
functions do not create form control if it is missing, but rather only set/modify existing form control value. So, just add new controls to empty FormArray
:
public cancel() {
const existingItems = this.group.get("items") as FormArray;
while (existingItems.length) {
existingItems.removeAt(0);
}
// Even adding a new FormGroup to the array, the exception remains.
// existingItems.push(this.fb.group({})););
// Here the error when trying to set the FormArray value
this.group.patchValue(this.originalFormData.value);
this.originalFormData.value.items.forEach(item => {
existingItems.push(this.fb.group(item));
});
}
STACKBLITZ: https://stackblitz.com/edit/angular-rsglab?file=app%2Fhello.component.ts
来源:https://stackoverflow.com/questions/49017027/cannot-set-initial-form-values-into-formarray