【问题标题】:Input mask through directive通过指令输入掩码
【发布时间】:2018-01-04 07:04:09
【问题描述】:

我希望输入遵循以下格式:

[00-23]:[00-59]

我们使用 Angular 2.4,因此我们没有可用的 pattern 指令,我无法使用外部库 (primeNG)。

所以我正在尝试为此制定指令:

@HostListener('keyup', ['$event']) onKeyUp(event) {
    var newVal = this.el.nativeElement.value.replace(/\D/g, '');
    var rawValue = newVal;
    // show default format for empty value
    if(newVal.length === 0) {
        newVal = '00:00';
    } 
    // don't show colon for empty groups at the end
    else if(newVal.length === 1) {
        newVal = newVal.replace(/^(\d{1})/, '00:0$1');
    } else {
        newVal = newVal.replace(/^(\d{2})(\d{2})/, '$1:$2');
    }
    // set the new value
    this.el.nativeElement.value = newVal;
}

这适用于我输入的前 2 位数字。

起始字符串:

00:00

按小键盘 1:

00:01

按小键盘 2:

00:12

但是在第三个数字上我得到:

00:123

而不是01:2300:1234 而不是12:34

退格按预期工作。

仅使用指令是否可以解决此问题?

【问题讨论】:

    标签: regex angular typescript angular-directive


    【解决方案1】:

    在最后的拒绝中尝试replace(/^(\d{0,2})(\d{0,2})/g, '$1:$2')。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 2016-01-30
      • 1970-01-01
      • 2020-08-15
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多