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
的值。它看起来很好,并且初始化正确。
{
"isActive": true,
"items": [
{
"user": "Walter",
"ctrlName": "Orders",
"date": "2018-03-18T23:00:00.000Z"
}
}
发布于 2018-02-28 05:16:57
如果从表单数组中删除项,则需要重新添加它们,因为如果缺少表单控件,setValue
或patchValue
函数不会创建它,而只是设置/修改现有的表单控件值。因此,只需将新控件添加到空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
复制相似问题