通过指令输入掩码

Input mask through directive

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

[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');
    } else {
        newVal = newVal.replace(/^(\d{2})(\d{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

退格键按预期工作。

是否有仅使用一个指令就可以解决此问题的方法?

在最后一个 rejex 尝试 replace(/^(\d{0,2})(\d{0,2})/g, ':')。希望这会有所帮助。