Reputation: 43
Seriously stumped here. I have two reactive forms in an Angular project.
Both have a select control with options stored in class variables.
One form uses simple option strings for employee options, as in:
["Dan Smith", "Mark Johnson", etc.]
The other form uses objects, as in:
[
{
value: "Dan Smith",
selected: false,
hidden: false
},
...
]
Stackblitz example: https://stackblitz.com/edit/angular-nks51y
In the example I have buttons for adding new random options, and setting a random selected option.
The buttons work on the form which uses simple strings, but don't work with the form using objects {}.
Additionally, the default value isn't set with the object form.
I know I'm missing something, but can't figure out what.
Upvotes: 1
Views: 757
Reputation: 692271
There are two mistakes in your code:
you should never set the selected
attribute of the select element. The whole point of the binding is that the option that is selected is the one set as the value of the form control. The model is the source of truth, not the view
The selected value (i.e. the value of the FormControl) is an object: the employee object itself. But the ngValue
used in the template is name.value
, i.e. a string which is the value of the employee object. An employee object can't be === to its value
property.
So the code should be:
<select formControlName="employeeName">
<option *ngFor="let employee of employeeNameObjectOptions" [ngValue]="employee" [hidden]="employee.hidden">
{{ employee.value }}
</option>
</select>
Note that I chose to rename name
to employee
since that's what the variables refereces: an employee, not a name. Good naming helps a lot to figure out mistakes.
Your fixed demo: https://stackblitz.com/edit/angular-pundfg?file=src%2Fapp%2Fapp.component.html
Upvotes: 2
Reputation: 9355
The ngValue
for your select option is a string [ngValue]="name.value"
and type does not match when you are setting an object to it.
<option *ngFor="let name of employeeNameObjectOptions" [selected]="name.selected" [ngValue]="name" [hidden]="name.hidden">
{{ name.value }}
</option>
Upvotes: 2