Reputation: 1262
I'm using Angular 2 FormGroups to manage my user input. If I'm looking to update select fields from old data, the select fields don't populate as expected. They only work if the last item in the list should be selected. Then the form shows that item from the FormGroup appropriately.
Here's the code for the select
<select formControlName="homeTeam">
<option>-- Choose a team --</option>
<option
*ngFor="let homeTeam of _teamsService.teamsForSchedule"
[ngValue]="homeTeam"
[selected]="homeTeam.$key===gameForm.value['homeTeam'].$key">
{{homeTeam.name}}
</option>
</select>
<label>Away Team</label>
<select formControlName="awayTeam">
<option >-- Choose a team --</option>
<option
*ngFor="let awayTeam of _teamsService.teamsForSchedule"
[ngValue]="awayTeam"
[selected]="awayTeam.$key===gameForm.value['awayTeam'].$key">
{{awayTeam.name}}
</option>
</select>
The [selected]
tag is what declares which item will be selected by default. As I said, it only works if the last item is the item to be selected by default.
Here's a screenshot of what I'm seeing
Here's the HTML I'm seeing when I inspect. As you can see, the selected is coming up on the second option tag, but for some reason, it doesn't display.
Home Team (displaying correctly)
<select formcontrolname="homeTeam" ng-reflect-name="homeTeam" class="ng-untouched ng-pristine ng-valid">
<option>-- Choose a team --</option>
<!--template bindings={
"ng-reflect-ng-for-of": "[object Object],[object Object],[object Object]"
}--><option value="1: Object" ng-reflect-ng-value="[object Object]">
Limozeen
</option><option value="2: Object" ng-reflect-ng-value="[object Object]">
Smash Bros
</option><option value="3: Object" ng-reflect-ng-value="[object Object]" ng-reflect-selected="true">
Thunder Thighs
</option>
</select>
Away Team (displaying incorrectly)
<select formcontrolname="awayTeam" ng-reflect-name="awayTeam" class="ng-pristine ng-valid ng-touched">
<option>-- Choose a team --</option>
<!--template bindings={
"ng-reflect-ng-for-of": "[object Object],[object Object],[object Object]"
}--><option value="1: Object" ng-reflect-ng-value="[object Object]">
Limozeen
</option><option value="2: Object" ng-reflect-ng-value="[object Object]" ng-reflect-selected="true">
Smash Bros
</option><option value="3: Object" ng-reflect-ng-value="[object Object]">
Thunder Thighs
</option>
</select>
Upvotes: 2
Views: 1748
Reputation: 1
You have put selected
property bound to some expression to every option populated via ngFor
directive. The last selected option is selected because you can select only one option from the select box.
If you bind the value
property then it will be selected if the value match the ngModel
expression's value.
Upvotes: 2