【问题标题】:Angular input [type]="'number'" always results in value being string角度输入 [type]="'number'" 始终导致值为字符串
【发布时间】:2023-04-02 21:51:02
【问题描述】:

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

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

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

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

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

StackBlitz

【问题讨论】:

    标签: angular property-binding


    【解决方案1】:

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

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

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

    【讨论】:

    • 这也不起作用,因为该值作为数字或字符串存储在模型中。
    • 如果你的值被声明为value: number | string;,它就可以工作
    • 谢谢,从 2016 年开始,这个问题仍然存在,这有点奇怪。这解决了问题,现在会解决。
    • 不抱歉,我不清楚,如果输入字段是文本字段,则该值将作为字符串保存到您的模型中。如果它是数字类型,它将被保存为数字。因此,如果用户输入一个值,然后动态切换类型,它将在您的模型中保持为数字或字符串,并且您刚刚在代码中引入了另一个错误。 stackblitz.com/edit/angular-g2mryc
    • @BrianBurton 是的,这是真的。我得到的类型是如何来自 API 并在之后被锁定的。所以没有与他们切换。
    【解决方案2】:

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

      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));
      }
    

    【讨论】:

      【解决方案3】:

      如果您想动态更改字段的输入类型,您可以试试这个。 在你的 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';
       }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 1970-01-01
        • 2018-09-19
        • 2020-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多