import { Directive, ElementRef, EventEmitter, HostListener, } from '@angular/core'; @Directive({ selector: '[format-payment-card]', }) export class FormatPaymentCardDirective { private _cardNumberFormat = /.{1,4}/g; constructor( private _elementRef: ElementRef, ) {} @HostListener('keyup') public onKeyUp() { const currentValue = this._elementRef.nativeElement.value.replace(/\s/g, ''); if (this._elementRef.nativeElement.value) { this._elementRef.nativeElement.value = currentValue.match(this._cardNumberFormat).join(' '); } } }