Good Day,
I am trying to create a dynamic reactive form, but I am struggling.
The concept is that the fields info will later be retrieved from a database (for now hardcoded for simplicity), and then the form is built based on this array.
My setup is as follows:
dynamicform.module.ts
export class DynamicForm {
constructor(
public fieldname: string,
public fielddescription: string,
public fieldtype: string,
public required: string
) {}
}
fetch-form.service.ts
...
...
export class FetchFormService {
constructor() { }
private _dynamicForm: DynamicForm[] = [
{
fieldname: 'fieldname_1',
fielddescription: 'Field Desc 1',
fieldtype: 'text',
required: '1'
},
{
fieldname: 'fieldname_2',
fielddescription: 'Field Desc 2',
fieldtype: 'text',
required: '1'
},
{
fieldname: 'fieldname_3',
fielddescription: 'Field Desc 3',
fieldtype: 'text',
required: '1'
}
];
get dynForm() {
return [...this._dynamicForm];
}
}
dynamic-form.page.ts
...
...
...
export class DynamicFormPage implements OnInit {
loadedForm: DynamicForm[];
dynamicForm: FormGroup;
...
...
...
then the init function:
ngOnInit() {
this.loadedForm = this.fetchService.dynForm;
this.dynamicForm = new FormGroup({
fieldname_1: new FormControl(null, {
updateOn: 'blur',
validators: [Validators.required]
}),
fieldname_2: new FormControl(null, {
updateOn: 'blur',
validators: [Validators.required]
}),
fieldname_3: new FormControl(null, {
updateOn: 'blur',
validators: [Validators.required]
})
});
}
and lastly I have the
dynamic-form.page.html
<ion-header>
<ion-toolbar>
<ion-title>Dynamic Form</ion-title>
<ion-buttons slot="primary">
<ion-button (click)="submitDynamicForm()">
<ion-icon name="checkmark" slot="icon-only"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<form [formGroup]="dynamicForm">
<ion-grid>
<ion-row>
<ion-col size-sm="6" offset-sm="3">
<ion-item>
<ion-label>
DYNAMIC FORM
</ion-label>
</ion-item>
</ion-col>
</ion-row>
<div *ngFor="let formItem of loadedForm">
<ion-row>
<ion-col size-sm="6" offset-sm="3">
<ion-item lines="none">
<ion-label position="floating">
{{formItem.fielddescription}}
</ion-label>
<ion-input
type="{{formItem.fieldtype}}"
formControlName="{{formItem.fieldname}}"
autocomplete
autocorrect
></ion-input>
</ion-item>
</ion-col>
</ion-row>
</div>
</ion-grid>
</form>
</ion-content>
the result:
then to note, currently the array is hardcoded in the fetch-form.service file, but in time it will be fetched with HTTP. Hardcoded now for simplicity.
ok so a couple of questions:
- Is this the correct way of building a dynamic form?
- How do I dynamically set the ‘fieldname’ in the FormGroup?
Would anyone be so kind as to provide me with some guidance and examples?
Thank you in advance!
Kind Regards