I am looking to generate a nested form
based on the following data:
The current data available is as follows:
mainObject = {
adminname: 'Saqib',
adminemail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40252d21292c002538212d302c256e232f2d">[email protected]</a>',
users: [
{ user_type: 'Adult', count: 3 },
{ user_type: 'Child', count: 1 },
{ user_type: 'Infant', count: 0 },
],
};
I aim to display nested forms for the counts mentioned in the Users Array. For instance, there should be 3 adult forms, 1 child form, and no Infant form as the Infant count is 0. These counts are flexible and can be adjusted, such as having 0 child forms and 1 infant form.
.html
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<input formControlName="name" placeholder="Enter Admin Name" />
<br />
<input formControlName="admin_email" placeholder="Enter Admin Email" />
<div formArrayName="users"gt;
<div *ngFor="let pro of myForm.get('users').controls; let i = index">
<br />
<div [formGroupName]="i" style="border: 1px solid; padding: 10px">
<div>User Type: {{ pro.value.user_type }}</div>
User Name:<br />
<input type="text" formControlName="user_name" /> <br />
Email:<br />
<input type="text" formControlName="user_email" />
</div>
</div>
</div>
<p>
<button type="submit">Submit</button>
</p>
</form>
.ts
myForm: FormGroup;
mainObject = {
adminname: 'Saqib',
adminemail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99c94989095b99c81989489959cd79a9694">[email protected]</a>',
users: [
{ user_type: 'Adult', count: 3 },
{ user_type: 'Child', count: 1 },
{ user_type: 'Infant', count: 0 },
],
};
// Generating forms based on user counts and types mentioned in the data.
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.formInit();
}
formInit() {
this.myForm = this.fb.group({
name: '',
admin_email: '',
users: this.fb.array(
this.mainObject.users.map((e) => this.newUsers(e.user_type, e.count))
),
});
}
get users(): FormArray {
return this.myForm.get('users') as FormArray;
}
newUsers(t, c): FormGroup {
console.log(t, c);
return this.fb.group({
user_type: t,
user_name: '',
user_email: '',
});
}
onSubmit() {
console.log(this.myForm.value);
}
For a clearer understanding, I have created an example on Stackblitz: