Miura-shi
Miura-shi

Reputation: 4519

Set Default Form Values from API Call

I get the following error when I try to initiate form control values in my ngOnInit method:

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]
        });
    });
}

I was able to get around this by using the setValue after returning a promise from my API service call like so and it works:

    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
            });
        });
    }

But doesn't seem to be the best way. How should I be binding data returned from an API to the form controls? It seems like I shouldn't use formGroups and possibly just use ngModels to bind data to the forms?

UPATE: with micronyks method, I tried the following:

    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]
            });
        });
    }

But it returns the following error in the console:

EXCEPTION: Uncaught (in promise): Error: Error in edit.template.html:12:10 caused by: formGroup expects a FormGroup instance. Please pass one in.

This seems to happen when it gets wrapped around the API call. Is the value of this being overwritten?

Upvotes: 1

Views: 3378

Answers (1)

Brivvirs
Brivvirs

Reputation: 2493

You need to set this.businessForm instance before angular2 renders view. Solution_1: Use *ngIf to show form only after you set instance of formBuilder. Solution_2: Set formbuilder this.businessForm with default values and then update your form when you get response from API.

Upvotes: 3

Related Questions