Ngx-bootstrap: Angular 4 - Autofocus of modal onload

Created on 12 Aug 2017  路  7Comments  路  Source: valor-software/ngx-bootstrap

Is there a way to auto-focus a specific textbox inside a modal when the modal is loaded/appears?
The autofocus in HTML works when the page reloads, but not in modals.

comp(modal)

Most helpful comment

I wrote a directive that seems to do the job:

import { Directive, ElementRef, AfterViewInit } from "@angular/core";

@Directive({
    selector: "[appFocus]"
})
export class FocusDirective implements AfterViewInit {
    constructor(private element: ElementRef) {}

    ngAfterViewInit() {
        this.element.nativeElement.focus();
    }
}

All 7 comments

The code jQuery('#username').focus(); works inside the specific method I use, but when I put it in ngOnInit and ngAfterViewInit, the auto focus of modal isn't working.

I noticed that the "autofocus" in HTML isn't working in Firefox, but working in Chrome but only for the first appear of the modal.

You can get access to field using ViewChild and then trigger focus. Unfortunately, this won't work without a small hack - call focus() inside setTimeout() like this
setTimeout(() => {this.input.nativeElement.focus();});

There is an option focus on the modal that you should disable to avoid strange behavior and then the above would work without the hack just place your code in ngAfterViewInit

you can call focus() in onShown handler

I got i worked by calling the focus() on the onShown event.
this.modal.onShown.pipe( tap(() => (document.querySelector('[autofocus]') as HTMLElement).focus()) ).subscribe());

I wrote a directive that seems to do the job:

import { Directive, ElementRef, AfterViewInit } from "@angular/core";

@Directive({
    selector: "[appFocus]"
})
export class FocusDirective implements AfterViewInit {
    constructor(private element: ElementRef) {}

    ngAfterViewInit() {
        this.element.nativeElement.focus();
    }
}
Was this page helpful?
0 / 5 - 0 ratings