Fra*_*sco 1 typescript angular2-forms angular
我有一个反应式表单,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);
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
尚未向该数组注册任何表单控件。如果您使用的是ngModel,则可能需要检查下一个刻度(例如,使用setTimeout)。
这个问题也有同样的问题,但是我无法解决。
更新-低于的值formGroup。看起来不错,并已正确初始化。
{
"isActive": true,
"items": [
{
"user": "Walter",
"ctrlName": "Orders",
"date": "2018-03-18T23:00:00.000Z"
}
}
Run Code Online (Sandbox Code Playgroud)
如果您从表单数组中删除项目,则您需要重新添加它们,因为setValue或patchValue函数不会在缺少表单控件时创建表单控件,而是仅设置/修改现有的表单控件值。因此,只需将新控件添加到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));
});
}
Run Code Online (Sandbox Code Playgroud)
STACKBLITZ:https://stackblitz.com/edit/angular-rsglab ? file = app%2Fhello.component.ts
| 归档时间: |
|
| 查看次数: |
1391 次 |
| 最近记录: |