【问题标题】:Input type number customization in angular 2Angular 2中的输入类型编号自定义
【发布时间】:2019-01-26 13:34:53
【问题描述】:

我正在尝试使用 angular2 中的 html5 输入类型号来实现时间选择器,如下所示:

<input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12">
<input type="number" [(ngModel)]="minutes" (change)="checkMinutes();" name="two" min="0" max="59">

在更改值时(手动输入或使用输入类型中的向上/向下箭头),应触发一个函数,以便我可以在打字稿中对其进行修改,以便以小时/分钟为单位的单个数字时间显示为两个-数字的。如:

如果我选择/输入值作为小时 5 和分钟 3,那么在函数调用之后,它应该在小时输入中显示为“05”,在分钟输入框中显示为“03”。但似乎存在一些问题,例如: this.hours 中没有更改的值。我怀疑我是否可以将数字类型操作为字符串?请帮忙。提前致谢。也欢迎任何替代解决方案。

public checkHours(){
  if (this.hours <= 9){
    this.hours = "0" + this.hours;
  }
}

public checkMinutes(){
  if (this.minutes <= 9){
    this.minutes = "0" + this.minutes;
  }
}

【问题讨论】:

  • 您能详细说明您面临的问题吗?

标签: angular html typescript angular5


【解决方案1】:

最快的是这个:

function twoDigits(value) {
  return ('0'  + value).slice(-2);
}

console.log(twoDigits('1'));
console.log(twoDigits('01'));

在你的情况下:

twoDigits(value: number) {
  value = ('0' + value).slice(-2);
}

叫它:

this.twoDigits(this.hours);

【讨论】:

    【解决方案2】:

    问题是因为您将小时数定义为数字,但在您的函数中为它分配了一个字符串值,但这是不正确的:

    你可以试试:

    public checkHours(){
      let hours=''
      if (this.hours <= 9){
        hours = "0" + this.hours;
      }
      console.log(hours)
    }
    
    public checkMinutes(){
      let minutes='';
      if (this.minutes <= 9){
        minutes = "0" + this.minutes;
      }
        console.log(minutes)
    }
    

    html:

    <input type="number" [(ngModel)]="hours" (change)="checkHours();" name="one" min="1" max="12">
    <input type="number" [(ngModel)]="minutes" (change)="checkMinutes();" name="two" min="0" max="59">
    

    工作demo

    【讨论】:

    • 在 JS 变量中没有输入:您可以从数字切换到字符串,反之亦然。在打字稿中,您将变量声明为两者,例如hours: number &amp; string;。问题不是由此而来的。
    • 你是对的,但问题是你不能将字符串分配给输入类型号,所以它不能正常工作。
    猜你喜欢
    • 2018-06-11
    • 2016-10-02
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2020-06-14
    • 2017-04-25
    相关资源
    最近更新 更多