Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number in [(ngModel)] in Angular 2? [duplicate]

Tags:

angular

How to get number in [(ngModel)] in Angular 2?

<select [(ngModel)]="levelNum">
    <option *ngFor="#level of levels" [value]="level.num">{{level.name}}</option>
</select>

levelNum:number;
levels:Array<Object> = [
    {num: 0, name: "AA"},
    {num: 1, name: "BB"}
];

I tried to add type="number" in different places.

 <select type="number" [(ngModel)]="levelNum">
    <option *ngFor="#level of levels" [value]="level.num">{{level.name}}</option>
</select>

and

 <select [(ngModel)]="levelNum">
    <option type="number" *ngFor="#level of levels" [value]="level.num">{{level.name}}</option>
</select>

But when I select a new item, levelNum still becomes a string.

like image 334
Hongbo Miao Avatar asked Feb 18 '16 20:02

Hongbo Miao


1 Answers

The Select with *ngFor in Angular2 seems to not work properly when using objects. They have opened the issue in github but it still hasn't been resolved.

Until this is fixed I would do something like changing the string value to a number whenever the select value is changed.

@Component({
  selector: 'my-app',
  template:`
    <h1>Selecting Number</h1>
    <select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()">
      <option *ngFor="#level of levels" [value]="level.num">{{level.name}}</option>
    </select>
    {{levelNum}}
  `,
})
export class AppComponent {
  levelNum:number;
  levels:Array<Object> = [
      {num: 0, name: "AA"},
      {num: 1, name: "BB"}
  ];

  toNumber(){
    this.levelNum = +this.levelNum;
    console.log(this.levelNum);
  }
}
like image 112
Gabu Avatar answered Oct 04 '22 22:10

Gabu