Angular input [type]="'number'" 总是导致值为字符串

Angular input [type]="'number'" always results in value being string

通常,我会这样声明输入类型(效果很好):

<input [(ngModel)]="input1" type="number" placeholder="Working"/>

然而,我希望类型是动​​态的,因此我使用 属性 绑定 [type]="objectType"。为了简化问题,我使用了 [type]="'number'".

<input [(ngModel)]="input2" [type]="'number'" placeholder="Not Working"/>

现在的问题是,每当我对 input2 进行更改时,它都会转换为字符串。 input1 不是这种情况 - 它仍然是预期行为的数字。如何使用 属性 类型绑定并防止它转换为字符串?

StackBlitz

这是一个已知问题(请参阅问题 #13243)。

目前一个简单的解决方法是对每种类型使用不同的输入:

@Input() public myInputType: string;
<input [(ngModel)]="value" type="number" *ngIf="myInputType === 'number'"/>
<input [(ngModel)]="value" type="text" *ngIf="myInputType === 'text'"/>
<!-- ... -->

这是我 运行 也遇到过的一个已知错误,但目前唯一的解决方案是手动转换输入值。

  logValues() {
    // Manually cast it as an integer (or float if need be)
    if (this.input2Type == 'number')
      this.input2 = parseInt(this.input2.replace(/[^\d]/g, ''));

    console.log('input1 =>', this.input1);
    console.log('input1 type => ', typeof(this.input1));
    console.log('input2 =>', this.input2);
    console.log('input2 type => ', typeof(this.input2));
  }

如果您想动态更改字段的输入类型,您可以试试这个。 在你的 html

<input [type]="value">
<button (click)="onClick()">Change</button>

在您的 .ts 文件中

value: string;
constructor(){
this.value = 'string';
}

onClick() {
  if (this.value == 'string') {
  this.value = 'number';
 }
else {
  this.value = 'string';
 }
}