Ravinder Kumar
Ravinder Kumar

Reputation: 752

option tag returning string value instead of number for ngModel in Angular

HTML:

<select [(ngModel)]='i.PaycodeId'>
  <option *ngFor="let j of payCode" [value]='j.ID'>{{j.value}}</option>
</select>

payCode:

[{"ID":0,"value":"Cycle"},{"ID":1,"value":"Truck"},{"ID":2,"value":"Car"}]

In i.PaycodeId, through ngModel, it is setting numbers as string value not numbers like "1"/"2" while the value passed to select is object having ID's value as number. I want this value as number only.

Upvotes: 19

Views: 12354

Answers (2)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

Please check out Asaf Hananel's answer below - it's what you're probably looking for.


You could separate the binding out like this:

<select [ngModel]="i.PaycodeId" (ngModelChange)="onChangeSelection($event)">
  <option *ngFor="let j of payCode" [value]='j.ID'>{{j.value}}</option>
</select>

And in your Component:

onChangeSelection(selected) {
    this.i.PaycodeId = parseInt(selected);
}

Working Plunker for example usage

Upvotes: 9

Asaf Hananel
Asaf Hananel

Reputation: 7302

Instead of using [value], use [ngValue].

<select [(ngModel)]='i.PaycodeId'>
  <option *ngFor="let j of payCode" [ngValue]='j.ID'>{{j.value}}</option>
</select>

Upvotes: 57

Related Questions