2

I am using Angular 7. And when I try to bind the value of a select to a variable, the value is always parsed into something like "0: 25", "1: 50", "2: 75".

Example code below is for selecting a page size for a paginator. Where pageSizeOptions = [25, 50, 75, 100]. Expected behavior is that pageSize, bound to [(ngModel)], should contain a number type and not a string. Using [value] will return a stringified version of the value nd ngValue returns the "[index]: [value]" format.

    <select
      class="form-control"
      (change)="onSelectPageSize($event.target.value)"
      [ngModel]="pageSize"
    >

      <option *ngFor="let size of pageSizeOptions; let i = index" [ngValue]="size">
        {{ size }}
      </option>
    </select>
Alex Pappas
  • 2,377
  • 3
  • 24
  • 48
  • Can you please make a [Stackblitz](http://stackblitz.com) for this. – Zze Mar 12 '19 at 03:58
  • I'll try to find time reproducing it on a Stackblitz, currently just fixed it with manual parsing to int and using `[value]` instead of `[ngValue]`. – Alex Pappas Mar 12 '19 at 04:42
  • @ColdCerberus check it [here](https://stackblitz.com/edit/angular-mxjedo?file=src/app/app.component.html) – developer033 Mar 12 '19 at 04:55
  • @developer033, Thanks. It's weird that when I added an onchange event to `console.log` the `pageSize`, it's actually a number and not similar to what I have here locally. – Alex Pappas Mar 12 '19 at 09:50

1 Answers1

1

The problem is that you are using ngValue instead of value attribute .

<option *ngFor="let size of pageSizeOptions; let i = index" [value]="size">
    {{ size }}
  </option>

The difference between ngvalue and value attribute is that value is always string, where in ngValue you can pass object.

Refer this answer for more info Differences between value and ngValue in Angular 5

Hameed Syed
  • 3,939
  • 2
  • 21
  • 31