import { Directive , ElementRef , HostListener } from '@angular/core' ; @ Directive ( { selector : '[appTwoDigitDecimalNumber]' } ) export class TwoDigitDecimalNumberDirective { private regex : RegExp = new RegExp ( /^\d*\.?\d{0,2}$/g ) ; private specialKeys : Array < string > = [ 'Backspace' , 'Tab' , 'End' , 'Home' , '-' ] ; constructor ( private el ) { } @ HostListener ( 'keydown' , [ '$event' ] ) onKeyDown ( event ) { if ( this . specialKeys . indexOf ( event . key ) !== - 1 ) { return ; } let current = this . el . nativeElement . value ; let next = current . concat ( event . key ) ; if ( next && ! String ( next ) . match ( this . regex ) ) { event . preventDefault ( ) ; } } }