首页 文章

从API调用设置默认表单值

提问于
浏览
0

当我尝试在ngOnInit方法中启动表单控件值时出现以下错误:

Error

formGroup expects a FormGroup instance. Please pass one in.

Method

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调用时 . this 的值是否被覆盖?

1 回答

  • 2

    您需要在angular2渲染视图之前设置 this.businessForm 实例 . Solution_1:仅在设置了formBuilder的实例后才使用* ngIf显示表单 . Solution_2:使用默认值设置formbuilder this.businessForm ,然后在从API获得响应时更新表单 .

相关问题