Skip to content

Instantly share code, notes, and snippets.

@Graniron
Last active September 16, 2017 17:04
Show Gist options
  • Save Graniron/240bb25222ed55b8b1245e1573db9ac4 to your computer and use it in GitHub Desktop.
Save Graniron/240bb25222ed55b8b1245e1573db9ac4 to your computer and use it in GitHub Desktop.
Angular custom directive for masking input
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[credit-card]'
})
export class CreditCardDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
if(trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
}
let numbers = [];
for(let i = 0; i < trimmed.length; i += 4) {
numbers.push(trimmed.substr(i, 4));
}
input.value = numbers.join(' ');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment