The majority of select / option solutions for Angular 2 work in a way that we return the actual content, not the value
attribute. However, since I'm still learning Angular 2, I want to get the actual value
attribute on clicking a button. I managed to somewhat solve this issue, but I'm not sure if this is the correct approach.
Below is the example of how I'd like it to work:
<select #selectedCategory>
<option *ngFor=#category of categories [value]=category.id>{{category.name}}</option>
</select>
<button (click)=getValueFromSelect(selectedCategory.value)>
/* This returns the selected category.name, not the value attribute. */
The solution above creates the following HTML (note the lack of value
attribute on option
):
<select _ngcontent-oom-3=>
<!--template bindings={}-->
<option _ngcontent-oom-3=>stuff 1</option>
<option _ngcontent-oom-3=>stuff 2</option>
<option _ngcontent-oom-3=>stuff 3</option>
</select>
The solution below actually works, however, I need an ngModel
in order to make it work.
<select [(ngModel)]=selectedCategory>
<option *ngFor=#category of categories [value]=category.id>{{category.name}}</option>
</select>
<button (click)=getValueFromSelect(selectedCategory.value)>
/* This returns the value attribute correctly; however, do I really need a ngModel for one value? */
What is the correct way to approach this situation?
Thank you for your suggestions.