0
我收到以下错误,当我尝试启动我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]
});
});
}
我能够通过使用setValue来解决这个问题,在从我的API服务调用中返回一个承诺之后所以它的工作原理:
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: 与micronyks方法,我试过如下:
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调用。 这个的值是否被覆盖?
它工作?如果是这样,你只想知道最好的方法吗? – micronyks
@micronyks我的第二种方法的作品,但我正在寻找一个更干净的解决方案。我觉得必须有比在formGroup对象上运行setValue方法更好的方法。在我的API调用中解析出承诺后,是否有办法绑定formBuilder构造函数中的数据?当我尝试 –
时,我不断收到上面提到的错误,但我还没有尝试过,但您可以试试这个:this.businessForm = this.formBuilder.group({business_object_name:[response.data.business.business_name == undefined?'':response.data.business.business_name,Validators.required], ... });' – micronyks