Search code examples
angularngx-bootstrap

ngx bootstrap - focus input on modal open


I have a modal with an input text field and when I open the modal I want to focus the input (so the user and type straight away without selecting the box).

I read a few different ways to do this using ngx-bootstrap. I've tried a lot of them but none of them seem to work. The closest however is this one. So the code below highlights the field but doesn't select it.

Input field on modal:

<input autocomplete="off" list="autocompleteOff" type="text" class="text-input" id="childName" [(ngModel)]="childName" placeholder="Child's First Name" [autofocus]>

Code that opens the model (this is attached to a button (click) event):

// Open Create Child Modal
openModal(template: TemplateRef<any>) {
    this.clearChildData();
    this.modalRef = this.modalService.show(template);
    this.modalService.onShown.pipe( tap(() => (document.querySelector('[autofocus]') as HTMLElement).focus()) ).subscribe();
}

I have seen a demo of this working, so obviously there's something I'm missing or I'm wrong on, but not sure what that is?


Solution

  • I would say this is a timing issue. You need first to subscribe to onShown and then you can call modalService.show. Also you should add take(1) to the onShown pipe. Otherwise the focus will be set every time you show a modal using the modal service, even if the component (and the [autofocus] element) has been destroyed.