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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With