Project

General

Profile

1
import { Directive, ElementRef, Renderer, AfterViewInit, Input } from "@angular/core";
2

    
3
@Directive({
4
    selector: "[mydpfocus]"
5
})
6

    
7
export class FocusDirective implements AfterViewInit {
8
    @Input("mydpfocus") value: string;
9

    
10
    constructor(private el: ElementRef, private renderer: Renderer) {}
11

    
12
    // Focus to element: if value 0 = don't set focus, 1 = set only focus, 2 = set focus and set cursor position
13
    ngAfterViewInit() {
14
        if (this.value === "0") {
15
            return;
16
        }
17

    
18
        this.renderer.invokeElementMethod(this.el.nativeElement, "focus", []);
19

    
20
        // Set cursor position at the end of text if input element
21
        if (this.value === "2") {
22
            let len = this.el.nativeElement.value.length;
23
            this.el.nativeElement.setSelectionRange(len, len);
24
        }
25
    }
26
}
(1-1/2)