17

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.

2
  • what is the type of i.PaycodeId in the class? Jun 20, 2016 at 11:48
  • So sorry for it. <tr *ngFor='let i of bonusArray'> where bonusArray is an array or object which contains a number type value 'Paycode'. I am creating a table with the help of bonusArray array and drop down is one of it's column item. Now I contains an object with one of its property 'PaycodeId' and type of it is number. But when I select something from dropdown it returns my string instead of number as you can see it in my original post. Jun 21, 2016 at 2:37

2 Answers 2

52

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

<select [(ngModel)]='i.PaycodeId'>
  <option *ngFor="let j of payCode" [ngValue]='j.ID'>{{j.value}}</option>
</select>
7
  • 2
    I don't know why this is not marked as the correct answer, solves the problems of parsing the value on the modelChange event.
    – Danny908
    Mar 27, 2019 at 16:22
  • 1
    ngValue is working, should mark this corrent answer
    – Hiep Tran
    Jun 27, 2019 at 5:11
  • 1
    This works for me using reactive forms.. so no need for onChange tweak! Upvoted. Dec 9, 2019 at 17:28
  • In my case it did not help. Don't have idea why.
    – Alexander
    Jun 19, 2020 at 5:48
  • Really good, , should mark this as correct answer! Jan 7, 2021 at 10:43
9

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

2
  • 1
    I could have done this before but I was just wondering if there is any straight forward simple way. Thanks for your solution. Jun 21, 2016 at 2:53
  • it's not logical angular team should fix this, there the option must take the value even if its type is number Mar 20, 2021 at 16:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.