import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
    selector: '[NumberWithDecimal]'
})
export class NumberWithDecimalDirective {
    private regex: RegExp = new RegExp(/^([0-9 .]*)$/g);
    private specialKeys: Array<string> = ["Backspace", "Tab", "End", "Home", "ArrowLeft", "ArrowRight"];
    constructor(private el: ElementRef) { }

    @Input() Amount: boolean = false;

    @HostListener('keydown', ['$event'])
    onKeyDown(event: KeyboardEvent) {
        if (this.specialKeys.indexOf(event.key) !== -1)
            return;

        let current: string = this.el.nativeElement.value;
        let next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex))
            event.preventDefault();
    }
}

