Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular7 and NgbModal: how to remove default auto focus

we just upgraded our application to angular 7 and we noticed that all ngBootstrap modals have now a default autofocus on the close button like the following picture.

modal image

here is my code:

html modal code:

<form [formGroup]="storeForm" novalidate>     <div class="modal-content">         <div class="modal-header">             <h4 class="modal-title">Modal Test</h4>             <button type="button" class="close" aria-label="Close"                 (click)="activeModal.dismiss('Cross click')">                <span aria-hidden="true">&times;</span>             </button>         </div>         <div class="modal-body">             <h4>Todo</h4>         </div>         <div class="modal-footer">             <button role="button" type="submit" class="btn btn-primary"                 (click)="activeModal.close('Finish click')" prevent-double-                 submit>{{ 'store.add.finish' | translate }}</button>        </div>     </div> </form> 

and how is the modal called thanks to my component.ts

    const modal = this._modalService.open(ModalComponent, { backdrop:         'static', size: 'lg'});     modal.result.then(         (data) => {            // some code         },         () => {         }     ); 

My question is how can i remove this default autofocus that doesn't fit with our expected behaviour?

Thanks for the reading and please forgive the misspellings.

like image 285
Flow Avatar asked Dec 04 '18 13:12

Flow


Video Answer


1 Answers

The focus is needed to be within modal for accessibility and keyboard navigation reasons. By default the focus is on the first focusable element within modal, which in your case is the close button. You can add ngbAutofocus attribute to the element where you want the focus to be.

Focus management demo.

<button type="button" ngbAutofocus class="btn btn-danger"       (click)="modal.close('Ok click')">Ok</button> 

You can read more on github

like image 149
Kld Avatar answered Oct 09 '22 13:10

Kld