首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法将初始表单值设置为FormArray

无法将初始表单值设置为FormArray
EN

Stack Overflow用户
提问于 2018-02-28 04:02:51
回答 1查看 3.1K关注 0票数 1
代码语言:javascript
复制
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);  
   }

错误消息:

尚未向此数组注册表单控件。如果你正在使用ngModel,你可能想要勾选下一步(例如使用setTimeout)。

这个question也有同样的问题,但我不能在我的情况下解决它。

更新-低于formGroup的值。它看起来很好,并且初始化正确。

代码语言:javascript
复制
{
 "isActive": true,
 "items": [
  {
   "user": "Walter",
   "ctrlName": "Orders",
   "date": "2018-03-18T23:00:00.000Z"
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-28 05:16:57

如果从表单数组中删除项,则需要重新添加它们,因为如果缺少表单控件,setValuepatchValue函数不会创建它,而只是设置/修改现有的表单控件值。因此,只需将新控件添加到空FormArray

代码语言:javascript
复制
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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49017027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档