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

Issue

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.

Solution

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


You could seperate 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

Leave a Reply

(*) Required, Your email will not be published