Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - how to get value from select / option

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.

like image 496
uglycode Avatar asked Apr 21 '16 13:04

uglycode


2 Answers

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:

  • select: set value individually from ngModel (e1e44a9), closes #7975 #7978

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).

like image 108
Mark Rajcok Avatar answered Oct 13 '22 19:10

Mark Rajcok


You could use a control defined inline 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.

like image 32
Thierry Templier Avatar answered Oct 13 '22 19:10

Thierry Templier