I'm trying to create a form that contains a list of select controls (just for the sake of simplicity).
I'm not going to add new selects to the form, I just want to keep track of the selected option in each of the select controls.
This is the json I use to generate the select controls:
sports = [
{
sportId: '1',
desc: 'Football',
categories: [
{
categId: '1',
desc: 'U-18'
},
{
categId: '1',
desc: 'U-20'
},
{
categId: '2',
desc: 'U-23'
}
]
},
{
sportId: '2',
desc: 'Volleyball',
categories: [
{
categId: '3',
desc: 'Junior'
},
{
categId: '4',
desc: 'Youth'
}
]
},
{
sportId: '3',
desc: 'Tennis',
categories: [
{
categId: '5',
desc: 'Singles'
},
{
categId: '6',
desc: 'Doubles'
}
]
}
];
And this is the html of my form
<form [formGroup]="registrationForm"(submit)="save()">
<div class="form-group">
<label for="firstname">First Name</label>
<input
type="text"
class="form-control"
id="firstname"
formControlName="firstName"
placeholder="First Name"
/>
</div>
<div class="form-group">
<label for="lastname">Last Name</label>
<input
type="text"
class="form-control"
formControlName="lastName"
id="lastname"
placeholder="Last Name"
/>
</div>
<div class="form-group" *ngFor="let sport of sports; let i = index">
<label attr.for="sport_{{i}}">{{sport.desc}}</label>
<select class="form-control" id="sport_{{i}}">
<option value="0">Select one</option>
<option *ngFor="let cat of sport.categories" [value]="cat.categId">{{cat.desc}}</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Building the form for the firstName and lastName is straightforward:
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.registrationForm = this.fb.group({
firstName: '',
lastName: ''
});
}
But I'm not sure about how to keep track of the selected options on each of the different select controls.
I'd really appreciate it if you could help me here.
EDIT
Here's a demo