Cannot set initial form values into FormArray

南笙酒味 提交于 2021-02-19 23:55:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!