import { Directive, ElementRef, EventEmitter, HostListener, } from '@angular/core'; @Directive({ selector: '[format-card-expiry]', }) export class FormatCardExpiryDirective { private _cardExpiryFormat = /\d/g; private _specialKeys = [ 'Backspace', 'Delete', ]; constructor( private _elementRef: ElementRef, ) {} @HostListener('keyup', ['$event']) public onKeyUp(event: KeyboardEvent) { if (this._specialKeys.some((key) => key === event.key)) { return; } const currentValue = this._elementRef.nativeElement.value.replace(/\//g, ''); const formatted = [ currentValue.substring(0, 2), currentValue.substring(2), ]; if (this._elementRef.nativeElement.value) { this._elementRef.nativeElement.value = currentValue.length > 1 ? formatted.join('/') : formatted.join(''); } } }