number.directive.ts 936 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { Directive, ElementRef, HostListener } from '@angular/core';
  2. @Directive({
  3. selector: '[appNumber]'
  4. })
  5. export class NumberDirective {
  6. // Allow decimal numbers and negative values
  7. private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
  8. // Allow key codes for special events. Reflect :
  9. // Backspace, tab, end, home
  10. private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home', '-' ];
  11. constructor(private el: ElementRef) {
  12. }
  13. @HostListener('keydown', [ '$event' ])
  14. onKeyDown(event: KeyboardEvent) {
  15. // Allow Backspace, tab, end, and home keys
  16. if (this.specialKeys.indexOf(event.key) !== -1) {
  17. return;
  18. }
  19. if(this.el.nativeElement.value == '-') {
  20. alert('ffs');
  21. }
  22. let current: string = this.el.nativeElement.value;
  23. let next: string = current.concat(event.key);
  24. if (next && !String(next).match(this.regex)) {
  25. event.preventDefault();
  26. }
  27. }
  28. }