Last active
September 16, 2017 17:04
-
-
Save Graniron/240bb25222ed55b8b1245e1573db9ac4 to your computer and use it in GitHub Desktop.
Angular custom directive for masking input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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