1

I need to set the focus of a specific input field after the component initialization, and I'd like to have the inside text fully selected. Looking on the internet for some hint, I ended up writing a speficic directive, this way:

@Directive({
selector: '[focusControl]'})
export class FocusDirective {
@Input('focusControl') focusEvent: EventEmitter<boolean>;

constructor( @Inject(ElementRef) private element: ElementRef, private renderer: Renderer) {
}

ngOnInit() {
    this.focusEvent.subscribe(event => {
        this.renderer.invokeElementMethod(this.element.nativeElement, 'focus', []);
        if (this.element.nativeElement.tagName == "INPUT") {
            this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
        }            
    });
}}

In the template, obviously I set the directive on the element:

 <input type="text" class="form-control" tabindex="1" [focusControl]="userIdFocus" maxlength="32">      

Then, after the component's views are initialized, in the AfterViewInit callback, I try to set focus and select:

ngAfterViewInit() {
    this.userIdFocus.emit(true);
}                   

The problem is the field gets the focus, but the text is NOT selected. If I try to set the focus behind a click on a button, then the whole thing works corretcly.

I could I fix that?

Gio
  • 23
  • 1
  • 7
  • To select entire content of the input control upon focus, Have you tried to use I know this isn't Angular 2 directive but will it not solve your problem? Note "onClik". – meDev May 29 '17 at 17:20

1 Answers1

4

Are you using Chrome? As found in: https://stackoverflow.com/a/19498477

In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.

Based on your code, something like this should work:

setTimeout(() => {
  this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
}, 0);

Seems that slight delay in execution allows the browser to detect the focus, allowing select() to then be called.

Hope that helps! Just encountered the problem myself.

Payam
  • 41
  • 2
  • Thanks Payam, but it didn't work. To say better, it works randomly (at least it looks like random to me) as it did before isterting the timeout. I'm using Chrome – Gio May 25 '17 at 10:05