Angular7 and NgbModal: how to remove default auto focus

人走茶凉 提交于 2019-12-12 11:13:49

问题


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.

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.


回答1:


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




回答2:


It's an ugly hack, but you can add a non visible element as the first element:

<input type="text" style="display:none" />



回答3:


template.html

<button type="button" aria-label="Close">Close</button>

styles.css

button[aria-label="Close"] {
  &:focus {
    outline: none;
  }
}


来源:https://stackoverflow.com/questions/53613974/angular7-and-ngbmodal-how-to-remove-default-auto-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!