Tarun Patel
Tarun Patel

Reputation: 253

Loading dynamic Reactive Forms , doesn't wait for the http call to complete

I am trying to load a dynamic fields forms based on the input from an http services (which is supposed to provide meta data of what fields to load with what name and type of fields etc). Hence i have to build the formGroup dynamically in ngOnInit() once i receive the http-response with the form meta-data.

When I hard-code this meta-data object and return through an Observable from the data-service, the component dynamically-builds the form in ngOnInt, however as soon as i move the call of the data service to live a http service, the page load seems to happen before the http call responds back and hence the form doesn't load the fields. I first get the following error on the console :

 ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

I have observed that eventually the http-call would have responded (say in just 11milli-seconds) and based on the .subscribe function it creates the formGroup (which is of no use now sine the page is rendered blank without any fields).

 formGroup = {};
 data:Array<FormField>;
 form: FormGroup;
 ngOnInit() {
 // dis --> is the data service
 this.dis.getFieldsData().subscribe(respose=>{
     this.data=respose;
     this.objectProps =
        Object.values(this.data)
        .map(prop => {
          return Object.assign({},{key:prop.name}, prop);
        });
       for(let prop of Object.values(this.objectProps)) {
                     this.formGroup[prop.name] = new FormControl(prop || '', 
                    this.mapValidators(prop.validation));
                   } //below is where the form is assigned the dynamically built  formGroup
                     this.form = new FormGroup(this.formGroup); 
});
 } 

Upvotes: 2

Views: 4059

Answers (2)

Kirubel
Kirubel

Reputation: 1627

You can use something like isFormReady boolean variable. So in your html put *ngIf="isFormReady" then in your component

this.form = new FormGroup(this.formGroup);
this.isFormReady = true;

Upvotes: 2

VadimB
VadimB

Reputation: 5711

You can create empty FormGroup on init: this.form = new FormGroup({});

and then fill this form dynamically with controls when event pass:

this.form.addControl('some-key', new FormControl(''));

Upvotes: 0

Related Questions