Improve modal focus handling with NgbAutoFocus directive and first element focus

  • Allow users to set the initial focus inside the modal with NgbAutoFocus directive.
<!-- will be focused after the modal opens -->
<input type="text" ngbAutoFocus />
  • If there is no ngbAutoFocus in the modal, focus first focusable element by default. Allow user to cancel this behaviour and focus nothing by doing
modal.open(content, {focusFirst: false})
  • add a demo for focus handling in a separate PR

Not sure if this is a breaking change and not sure if we need ngbAutoFocus as a directive or a simple attribute would do.

2 thoughts on “Improve modal focus handling with NgbAutoFocus directive and first element focus

  1. hi folks, just wondering why the custom (and new) directive instead of using native autofocus?
    (I know that part, it does not work in first place, dynamic content behaviour, etc). But in the guts of the pending PR plain selector is being using:

    const elementToFocus = this._elRef.nativeElement.querySelector(`[ngbAutofocus]`) as HTMLElement;

    https://github.com/ng-bootstrap/ng-bootstrap/pull/2737/files#diff-8fb1cd1cc4cf9a5207c30f1474b6c8b9R67

    and I think this does not differ much from:

    const elementToFocus = this._elRef.nativeElement.querySelector(`[autofocus]`) as HTMLElement;

    Thanks!

  2. @maxokorokov : modal.open(content, {focusFirst: false}) is this feature removed from V4, because i am not able to see focusFirst property in NgbModalOptions. if yes how to achieve a situation where i don’t want to set any default focus but should be able to close the modal with ESC key.