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"
}
}