我有一个被动表单,cancel
必须将初始表单值再次设置到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);
}
错误消息:
此阵列尚未注册表单控件。如果您正在使用ngModel,则可能需要检查下一个刻度(例如,使用setTimeout)。
此question有同样的问题,但我无法解决这个问题。
更新 - 低于formGroup
的值。它看起来很好并且正确初始化。
{
"isActive": true,
"items": [
{
"user": "Walter",
"ctrlName": "Orders",
"date": "2018-03-18T23:00:00.000Z"
}
}
答案 0 :(得分:4)
如果从表单数组中删除项目,则需要重新添加它们,因为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