Angular 2 - how to get value from select / option

Most select / option solutions for Angular 2 work in such 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 when the button is clicked. I managed to solve this problem somewhat, but I'm not sure if this is the right approach. The following is an example of how I want 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. */ 

In the above solution, the following HTML is created (note the absence of the 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 really works, however I need ngModel for it to 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 right approach to this situation?

Thanks for your suggestions.

+5
source share
3 answers

As discussed in the comments, the example β€œhow do I need to work this” works:

 <select #selectedCategory> <option *ngFor="#category of categories" [value]="category.id"> {{category.name}} </option> </select> <button (click)="getValueFromSelect(selectedCategory.value)">click me</button> 

Plunker

However, for this we must use beta.15. For more information see changelog for beta .15:


I prefer this approach, as it does not add properties to the component, and we do not need to use the <form> (as in @Thierry's answer).

+10
source

You can use the control defined on the line with the ngControl directive:

 <form> <select #categoriesCtrl="ngForm" ngControl="categoriesCtrl"> <option *ngFor="#category of categories" [value]="category.id"> {{category.name}} </option> </select> <button (click)="getValueFromSelect(categoriesCtrl.value)"> </form> 

See this plunkr: https://plnkr.co/edit/uWUS9RaGJ34PiXTJ1kPd?p=preview .

+1
source

you can use change event

 <form> <select #categoriesCtrl (change)='SelectedValue = categoriesCtrl.value'> <option *ngFor="#category of categories" [value]="category.id">{{category.name}}</option> </select> <button (click)="getValueFromSelect()">Get value</button> </form> 

Working example https://plnkr.co/edit/dQZgSyw6uc67UNhNDlZv?p=preview

0
source

Source: https://habr.com/ru/post/1247626/


All Articles