I want to mask my input value, basically I have an input field for credit card expiry date and want to mask it in format mm/yy, this is what I had tried :
input-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)}`);
}
}
}
I got my expected output, but the problem is when using backspace on input field, it messed up, here is my demo on stackblitz, how to solve this? or is there any better approach on input mask?