69

I have a form with different selects like :

<select [(ngModel)]="selected.isConnected" (ngModelChange)="formChanged()" name="etat" id="etat" class="form-control">
    <option value="0">Not connected</option>
    <option value="1">Connected</option>
</select> 

My backend expect to receive an int in the "isConnected" attribute. Unfortunately as soon as I change the value of the select the attribute is cast to a string :

{
    isConnected : "0", // 0 expected
}

For standard <input> I could use type="number" but for a <select> I'm clueless.

Is there a way to force angular 2 to cast the data to int ?

3
  • would you please show formChanged() method?
    – micronyks
    Sep 13, 2016 at 15:52
  • Use ng-options. Using nested option will always set the model as a string. That's documented.
    – JB Nizet
    Sep 13, 2016 at 15:54
  • ng-option does not exist in Angular2. Maybe you mean using [ngValue] instead of [value]. Mar 24, 2017 at 10:42

6 Answers 6

181

Use [ngValue] instead of "value":

<select [(ngModel)]="selected.isConnected" id="etat">
    <option [ngValue]="0">Not connected</option>
    <option [ngValue]="1">Connected</option>
</select> 
3
  • 3
    Works and is as simple as would be expected from angular.
    – Algis
    Aug 9, 2017 at 8:32
  • 1
    It does work in Angular 6. Make sure the type of your ngModel and ngValue are both number. Mine was failing b/c ngValue was a string. (duh) @BrianLeach
    – Jess
    Nov 28, 2018 at 16:56
  • 2
    This can also be used by AngularJs for anyone still using that... just remove the square brackets around the ng-value attribute.
    – dalcam
    Aug 15, 2019 at 2:41
4

If you want cast it within formChanged() method (Which you haven't provided yet). You should use + symbol as shown below,

formChanged(): void {
    selected.isConnected = +selected.isConnected;
    ...
}
4
  • I was hoping it was possible to tell angular to automatically parse it. But using formChanged() could indeed do the trick
    – grunk
    Sep 13, 2016 at 16:20
  • What i did : this.selected.myKey = Number(this.selected.myKey);
    – grunk
    Sep 14, 2016 at 6:36
  • You just need to put + sign. Thats it !
    – micronyks
    Sep 14, 2016 at 16:22
  • Beware that this does not handle nulls, so an input of "null" will yield NaN Jun 28, 2021 at 18:06
2

No, sadly you're forced to parse it on your own in the formChanged() method, since you always get a string back from the select.

You could try it with something like this:

formChanged(): void {
    selected.isConnected = parseInt(selected.isConnected);
    // ...
}
0

You can send a Number variable to select and assign the value for that select element. Then if you want to capture the value when it changes, you can add (change) event to select and retrieve the value as shown below.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<select value="{{isConnected}}" (change)="printConnected($event.target.value)" name="etat" id="etat" class="form-control">
          <option value="0">Not connected</option>
          <option value="1">Connected</option>
        </select>
        <div *ngIf="changed">You've selected {{isConnected}}<div>`
})
export class AppComponent {

  isConnected : number = 1;
  changed : boolean = false;
  printConnected(value){
this.isConnected = value;
this.changed=true;
  }

}

You can view an example at http://plnkr.co/edit/xO2mrTdpTGufkgXqdhYD?p=preview

0

I am using reactive bindings and do not want to use [(ngModel)]. Instead I created a piped observable that uses JSON.parse(value) (because +value doesn't handle "null"):

*.component.html:

    <div class="col-lg-4 form-group">
      <label>Group Type</label>
      <select class="form-control" (change)="groupType$.next($event.target.value)">
        <option [value]="null"></option>
        <option *ngFor="let groupType of filterData.groupTypes" [value]="groupType.id">{{groupType.label}}</option>
      </select>
    </div>
    <div class="col-lg-4 form-group" *ngIf="filteredGroups$ | async as groupOptions">
      <label>Group</label>
      <select class="form-control" (change)="group$.next($event.target.value)">
        <option [value]="null"></option>
        <option *ngFor="let group of groupOptions" [value]="group.id">{{group.label}}</option>
      </select>
    </div>
    <div class="col-lg-4 form-group">
      <label>Status</label>
      <select class="form-control" (change)="status$.next($event.target.value)">
        <option [value]="null"></option>
        <option *ngFor="let status of filterData.statuses" [value]="status.id">{{status.label}}</option>
      </select>
    </div>

*.component.ts:

  group$ = new BehaviorSubject<string>(null);
  groupId$ = this.group$.pipe(
    map((groupId: string) => JSON.parse(groupId) as number)
  );
  groupType$ = new BehaviorSubject<string>(null);
  groupTypeId$ = this.groupType$.pipe(
    map((typeId: string) => JSON.parse(typeId) as number)
  );
  status$ = new BehaviorSubject<string>(null);
  statusId$ = this.status$.pipe(
    map((statusId: string) => JSON.parse(statusId) as number)
  );
0

[ngValue] is intended for objects. It generates an artificial option value even for numeric constants. For those who might be concerned about tests or readability, you can expand two way binding microsyntax

    <select [ngModel]="selected.isConnected" 
            (ngModelChange)="selected.isConnected=$event && +$event" id="etat">
        <option value="0">Not connected</option>
        <option value="1">Connected</option>
    </select> 

Your Answer

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.