raj m
raj m

Reputation: 2023

How to get dropdown list selected value in form element in angular2

Below My code has one form with few inputs. I want get all the values on submit. Able to get all the element values using ngModel. How can I get select option selected value.

 <form #f="ngForm" (ngSubmit) = "saveData(f)">
  <fieldset>
   <legend>Your Details:</legend>
   <label>Name: <input type="text" name="name" size="30" maxlength="100" [(ngModel)] = "name"></label><br />
   <label>Email: <input type="email" name="email" size="30" maxlength="100" [(ngModel)] = "email"></label><br />
   <label>Password: <input type="password" name="password" size="30" maxlength="100" [(ngModel)] = "password"></label><br />
   <select>
     <option *ngFor = "let combo of combos" value={{combo}}>{{combo}}
     </option>
   </select>
 <input type="submit" value="Save"/>
</fieldset><br />
</form>

Upvotes: 1

Views: 8563

Answers (3)

Use [(ngModel)] to bind selected value with variable OR Model as below:

<select [(ngModel)]="model.combo">
 <option *ngFor = "let combo of combos" value={{combo}}>{{combo}}
 </option>
</select>

OR

let comboValue : any;

<select [(ngModel)]="comboValue">
 <option *ngFor = "let combo of combos" value={{combo}}>{{combo}}
 </option>
</select>

Upvotes: 0

raj m
raj m

Reputation: 2023

problem was not setting the name property.

<select [(ngModel)]="gender" name="gender">
   <option *ngFor = "let combo of combos" [value]=combo>{{combo}}
   </option>
</select>

Upvotes: 0

Manh Le
Manh Le

Reputation: 1650

I think it should be [value]="combo"

<select #selCombo>
  <option *ngFor = "let combo of combos" [value]="combo">{{combo}}
  </option>
</select>

Then get selected value in HTML side (if you don't want to write in component)

<div>{{selCombo.value}}</div>

Upvotes: 2

Related Questions