参见英文答案 >
Binding select element to object in Angular9个
如何在Angular 2中的[(ngModel)]中获取数字?
如何在Angular 2中的[(ngModel)]中获取数字?
<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"} ];
我试着在不同的地方添加type =“number”.
<select type="number" [(ngModel)]="levelNum"> <option *ngFor="#level of levels" [value]="level.num">{{level.name}}</option> </select>
和
<select [(ngModel)]="levelNum"> <option type="number" *ngFor="#level of levels" [value]="level.num">{{level.name}}</option> </select>
但是当我选择一个新项目时,levelNum仍然成为一个字符串.
使用对象时,Angular2中的Select with * ngFor似乎无法正常工作.他们已经在
github开放了这个问题,但仍未解决.
在修复此问题之前,我会做一些事情,比如每当更改选择值时将字符串值更改为数字.
@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: "BB"} ]; toNumber(){ this.levelNum = +this.levelNum; console.log(this.levelNum); } }