当我尝试在ngOnInit方法中启动表单控件值时出现以下错误:
错误
formGroup expects a FormGroup instance. Please pass one in.
方式
ngOnInit() {
this.getBusinessData().then((response:any) => {
this.businessForm = this.formBuilder.group({
'business_name': [response.data.business_name, Validators.required],
'email': [response.data.email, Validators.required]
});
});
}
我能够通过我的API服务调用返回一个promise后使用setValue来解决这个问题,并且它可以工作:
ngOnInit() {
// Build the form
this.businessForm = this.formBuilder.group({
'business_name' : ['', Validators.required],
'email' : ['', Validators.required],
});
// Fetch data for the view
this.getBusinessData().then((response:any) => {
this.businessForm.setValue({
business_name: response.data.business.business_name,
email: response.data.business.email
});
});
}
但似乎并不是最好的方式。我应该如何将从API返回的数据绑定到表单控件?看来我不应该使用formGroups,可能只是使用ngModels将数据绑定到表单?
UPATE: 用micryks方法,我尝试了以下方法:
ngOnInit() {
// Bind data to the form
this.getBusinessData().then((response:any) => {
this.businessForm = this.formBuilder.group({
'business_name' : [response.data.business.business_name==undefined?'': response.data.business.business_name, Validators.required],
'email' : [response.data.business.email==undefined?'': response.data.business.email, Validators.required]
});
});
}
但它在控制台中返回以下错误:
EXCEPTION: Uncaught (in promise): Error: Error in edit.template.html:12:10 caused by: formGroup expects a FormGroup instance. Please pass one in.
这似乎发生在API调用时。 此的值是否被覆盖?
答案 0 :(得分:2)
您需要在angular2呈现视图之前设置this.businessForm
实例。
Solution_1:仅在设置了formBuilder的实例后才使用* ngIf显示表单。
Solution_2:使用默认值设置formbuilder this.businessForm
,然后在从API获得响应时更新您的表单。