Project

General

Profile

1 61381 k.triantaf
import { Directive, ElementRef, Input, HostListener, Renderer2 } from "@angular/core";
2
import { IMyInputAutoFill } from "../interfaces/my-input-auto-fill.interface";
3
4
@Directive({
5
    selector: "[myinputautofill]"
6
})
7
8
export class InputAutoFillDirective {
9
    @Input("myinputautofill") opts: IMyInputAutoFill;
10
11
    constructor(private el: ElementRef, private rndr: Renderer2) {}
12
13
    @HostListener("keyup", ["$event"]) onKeyUp(evt: KeyboardEvent) {
14
        if (!this.opts.enabled || evt.keyCode === 8 || evt.keyCode === 46) {
15
            return;
16
        }
17
18
        let val: string = this.getInputValue();
19
        let ews: boolean = this.endsWith(val, this.opts.separator);
20
        let parts: Array<string> = val.split(this.opts.separator);
21
        let idx: number = parts.length - 1;
22
23
        if (val.indexOf(this.opts.separator + this.opts.separator) !== -1) {
24
            return;
25
        }
26
27
        if (!ews && (val.length === this.getPartLength(0) || val.length === this.getPartLength(0) + this.getPartLength(1) + this.opts.separator.length)) {
28
            this.setInputValue(val + this.opts.separator);
29
        }
30
        else if (ews && parts[idx - 1].length < this.getPartLength(idx - 1) && this.isNumber(parts[idx - 1]) && (this.isDay(idx - 1) || this.isMonth(idx - 1))) {
31
            this.setInputValue(this.insertPos(val, val.length - 2, "0"));
32
        }
33
        else if (parts[idx].length < this.getPartLength(idx) && this.isNumber(parts[idx]) && (Number(parts[idx]) > 3 && this.isDay(idx) || Number(parts[idx]) > 1 && this.isMonth(idx))) {
34
            this.setInputValue(this.insertPos(val, val.length - 1, "0") + (idx < 2 ? this.opts.separator : ""));
35
        }
36
    }
37
38
    private endsWith(val: string, suffix: string): boolean {
39
        return val.indexOf(suffix, val.length - suffix.length) !== -1;
40
    }
41
42
    private insertPos(str: string, idx: number, val: string): string {
43
        return str.substr(0, idx) + val + str.substr(idx);
44
    }
45
46
    private getPartLength(idx: number): number {
47
        return this.opts.formatParts[idx].length;
48
    }
49
50
    private isNumber(val: string): boolean {
51
        return val.match(/[1-9]/) !== null;
52
    }
53
54
    private isDay(idx: number): boolean {
55
        return this.opts.formatParts[idx].indexOf("d") !== -1;
56
    }
57
58
    private isMonth(idx: number): boolean {
59
        return this.opts.formatParts[idx].indexOf("m") !== -1 && this.opts.formatParts[idx].length === 2;
60
    }
61
62
    private getInputValue(): string {
63
        return this.el.nativeElement.value;
64
    }
65
66
    private setInputValue(val: string): void {
67
      console.info(val);
68
        this.rndr.setProperty(this.el.nativeElement, "value", val);
69
        //this.rndr.setProperty(this.el.nativeElement, "value", val);
70
    }
71
}