Angular 2 Reactive Form嵌套组在重置抛出错误

时间:2017-11-14 08:59:30

标签: forms angular angular2-forms angular-reactive-forms formgroups

我有这个表单组:

Id: [null],
Nominativo: [null, [Validators.required, Validators.maxLength(100)]],
Area: fb.group({
    Id: [null]
})

当我尝试使用此模型重置表单时:

Id: 1,
Nominativo: 'Test'
Area: null

区域空值抛出异常" TypeError:无法读取属性' Id' of null"。我的预期结果是所有Area值变为null。我可以避免这个问题吗?当所有嵌套模型全部为空时,我的服务器响应为null

2 个答案:

答案 0 :(得分:0)

我建议做这样的事情:

area.model.ts

export class Area {
 id: string;
}

data.model.ts

export class DataModel {
 id: string;
 nominativo: string;
 area: Area;
}

form.model.ts

export class FormModel {
 id: string;
 nominativo: string;
 area?: Area;
}

数据model.service.ts

@Injectable()
export class DataModelService {
  toFormModel(dataModel: DataModel): FormModel {
    const form: FormModel = new FormModel();
    form.id = dataModel.id;
    form.nominativo = dataModel.nominativo;
    if (dataModel.area) {
      form.area = dataModel.area;
    }
    return form;
 }
}

form.component.ts

constructor(dataModelService: DataModelService,
            dataApi: dataApiService,
            fb: FormBuilder) {
  this.form = this.fb.group({
    id: '',
    nominativo: '',
    area: this.fb.group({
      id: ''
    })
  });

  this.dataApi.getData()
    .map((data: DataModel) => this.dataModelService.toFormModel(data))
    .subscribe((formData) => {
       this.form.patchValue(formData);
    });
}

答案 1 :(得分:0)

我认为没有一个简单的清洁解决方案。您需要迭代对象属性并手动设置值。所以像这样:

resetVal = {Id:1, Nominativo: 'Test', Area: null }

当您收到数据时,首先检查Area是否为空,如果是,请将formcontrols设置为该表单组中的null。如果没有,则将您从后端获得的值设置为表单组:

this.areaCtrl = this.myForm.controls.Area as FormGroup;

this.myForm.patchValue({
  Id: this.resetVal.Id,
  Nominativo: this.resetVal.Nominativo,
}) 
if(this.resetVal.Area === null) {
  this.areaCtrl.patchValue({
    Id: null
  })
}
else {
  for(let a in this.resetVal.Area) {
    this.areaCtrl.patchValue({         
      [a]:this.resetVal.Area[a]
    })
  }
}

<强> DEMO