从 API 调用中设置默认表单值

Set Default Form Values from API Call

当我尝试在我的 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 服务调用返回一个承诺后,我能够通过使用 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 将数据绑定到表单?

更新: 使用 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]
            });
        });
    }

但是它 returns 在控制台中出现以下错误:

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的值是否被覆盖?

您需要在 angular2 渲染视图之前设置 this.businessForm 实例。 Solution_1: 使用 *ngIf 仅在设置 formBuilder 实例后显示表单。 Solution_2:使用默认值设置表单生成器 this.businessForm,然后在收到 API 的响应时更新表单。