I'm creating dynamic form control in angular with this data
"data": [
{
"sno": 1,
"name": "name",
"nameLabel": "Name",
"isRequired": 1,
"maxLen": 50,
"order": 1,
},
{
"sno": 2,
"name": "desc",
"nameLabel": "Description",
"isRequired": 1,
"maxLen": 50,
"order": 2,
},
..
..
in Oninit method
rForm: FormGroup;
Data:any=[];
ngOnInit(): void {
let json = {
....
}
this.Service.Info(json).subscribe((data) => {
this.Data=data;
for (const field of this.Data) {
let validators = [];
validators.push(Validators.required);
this.rForm.addControl(field.name, this.fb.control('', validators));
}
});
}
in html
component using this
<form *ngIf="Data?.length" [formGroup]="rForm">
<div >
<div >
<label for="">Email</label>
<input type="text" placeholder="Email">
</div>
</div>
but unable to render dynamic fields
ERROR Error: formGroup expects a FormGroup instance. Please pass one in.
Any solution to fix this issue. Thanks
CodePudding user response:
First your ngOnInit code should be like
ngOnInit(): void {
this.Service.Info(json).subscribe((data) => {
this.Data = data.data;
for (const field of this.Data) {
let validators = [];
validators.push(Validators.required);
this.rForm.addControl(field.name, this.fb.control('', validators));
}
});
}
HTML
<form *ngIf="Data != null && Data.length > 0" [formGroup]="rForm">
<div >
<div *ngFor="let control of rForm.value | keyvalue">
<label for="">Email</label>
<input type="text" placeholder="Email" [formControlName]="control.key">
<span *ngIf="form.get(control.key).errors?.required">Field is required</span>
</div>
</div>
</form>
And other points you need to make sure is
- [formControlName]="email" which passes the value of the property email which doesn't exist. What you need is to pass the string email like [formControlName]="'email'" or simpler formControlName="email"