Class User is defined as follows:
export class User {
name: string
details: Details;
}
Class Details is defined as follows:
export class Details {
country: Country;
major : Major;
}
Class Major is defined as follows:
export class Major{
department : string;
subject : Subject;
}
The form structure is created as follows:
userForm : FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit(): void {
this.createUserForm();
}
createUserForm() {
this.userForm = this.fb.group(
{
name:new FormControl(null, Validators.required),
details: this.fb.array([this.createDetailsForm()])
}
);
}
createDetailsForm(): FormGroup {
return this.fb.group({
country:this.createCountryForm(),
major:this.fb.array([this.createMajorForm()])
})
}
createCountryForm(): FormGroup {
return this.fb.group({
id: new FormControl(null)
})
}
createMajorForm(): FormGroup {
return this.fb.group({
department:new FormControl(null),
subject: this.createSubjectForm()
});
}
createSubjectForm(): FormGroup {
return this.fb.group({
id: new FormControl(null)
})
}
JSON to create a user on the server side:
{
"name": "Kevin",
"details": [{
"country": {
"id": 1 //used in select box. It is not getting patched from user form.(problem area)
},
"major": [{
"department": "Science",
"subject": {
"id": 2 //used in select box. It is not getting patched from user form. (problem area)
}
}]
}]
}
Definition of Class Country:
export class Country{
id: number;
name: string;
}
Data for countries:
countries : Country [] = [
{id:1, name:"Serbia"},
{id:2, name:"Slovenia"},
{id:3,name:"India"}
]
HTML part for selecting country:
<div [formGroupName]="country">
<select>
<option
*ngFor="let c of countries"
[Value]="c.id"
>
{{ c.name }}
</option>
</select>
</div>
Definition of Class Subject:
export class Subject{
id:number;
name:string;
}
Data for subjects:
subjects : Subject [] = [
{id:1, name:"Chemistry"},
{id:2, name:"Physics"},
{id:3, name:"Botany"}
]
HTML part for selecting subject:
<div [formGroupName]="subject">
<select>
<option
*ngFor="let s of subjects"
[Value]="s.id"
>
{{ s.name }}
</option>
</select>
</div>
Explanation of Problem: The user details form contains nested form arrays and form groups. While populating the select boxes for both subject and country works, setting the 'id' value for both subject and country in the user form is not successful.
The current method used for patching the user form is:
this.service.registerUser(this.userForm.value);
What is the correct way to set the select box values? Is there any mistake in the TypeScript or HTML code? Do additional steps need to be taken to set the 'id' value from the select boxes for both subject and country in the user form? How to set controls inside the select boxes? Should the select box value be patched independently? The form will also be used for editing purposes, if that affects how values are set. Any suggestions or solutions would be greatly appreciated. Thank you in advance.