Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  139] [ 3]  / answers: 1 / hits: 35666  / 8 Years ago, thu, april 21, 2016, 12:00:00

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.


More From » angular

 Answers
3

As discussed in the comments, the how I'd like it to work example does work:



<select #selectedCategory>
<option *ngFor=#category of categories [value]=category.id>
{{category.name}}
</option>
</select>

<button (click)=getValueFromSelect(selectedCategory.value)>click me</button>


Plunker



However, we must use beta.15 for this to work. See the changelog for beta.15 for more info:








I prefer this approach since it does not add a property to the component, nor do we need to use a <form> tag (like in @Thierry's answer).


[#62449] Wednesday, April 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenyonmasonc

Total Points: 44
Total Questions: 117
Total Answers: 116

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;