我想屏蔽我的input价值,基本上我有一个信用卡到期日的输入字段,并想以格式屏蔽它mm/yy,这就是我尝试过的:
输入mask.directive.ts
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/\s+/g, '').slice(0, 4);
if (trimmed.length > 3) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
}
}
}
我得到了预期的输出,但问题是在输入字段上使用退格键时,它搞砸了,这是我在stackblitz 上的演示,如何解决这个问题?或者有没有更好的输入掩码方法?
GCT1015
呼唤远方
相关分类