Reputation: 253
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
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
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