I have a unique sample object that needs to be transformed into form controls:
[
{
"labelName": "Full Name",
"inputType": "textbox",
"inputValues": "",
"mandatory": "yes"
},
{
"labelName": "Email Address",
"inputType": "textbox",
"inputValues": "",
"mandatory": "yes"
},
{
"labelName": "Address 2",
"inputType": "textarea",
"inputValues": null,
"mandatory": "yes"
},
{
"labelName": "City",
"inputType": "dropdown",
"inputValues": null,
"mandatory": "no"
}
]
In order to create the form controls, I need to generate them based on the given object. Below is the code snippet for implementing this in TypeScript and HTML:
ts:
FormGroup: FormGroup;
this.fieldsData.forEach((ele, i) => {
form[ele?.labelName]=new FormControl('',[Validators.required]);
});
this.FormGroup=new FormGroup(form);
HTML:
<form [formGroup]="FormGroup">
<div *ngFor="let data of fieldsData">
<label>{{data.labelName}} </label>
<input type="text" formControlName="{{data.labelName}}">
</div>
<button class="btn-submit" type="button" [disabled]="!FormGroup.valid" style="margin-top: 20px" (click)="SubmitDemo()">
Submit
</button>
</form>
The challenge lies in applying validation based on the mandatory
key from the object. If it is set to "yes", then validation should be applied. Additionally, if the input type is 'textbox', it should be bound with an input type='text'
, or if it is a dropdown, it should be bound as a dropdown
control.
If you have any solutions, I would greatly appreciate it. Thank you!