How to fix the focus being reset to the top the page when the currently focused element is removed using ngIf in Angular?

Viewed 699

I am working on improving the accessibility of an Angular Application. There is a cancel button, if pressed will hide the button and display div with a warning and two buttons, yes and no. If pressed no, the warning disappears and the cancel button re-appears.

I will add a small sample code snippet below. Actual code is a little complex.

 <button *ngIf="!hideCancel" (click)="toggleWarning(true)" </button>

 <div *ngIf="hideCancel">
      <p>Are you sure you want to cancel?</p>
 <button> Yes </button>
 <button (click)="toggleWarning(false)"> No </button>
 </div>


 toggleWarning(flag: boolean) {
    if (flag) {
        document.getElementById('someWarning').innerHTML = 'Are you sure you want to cancel?';
    } else {
         document.getElementById('someWarning').innerHTML = '';
    }
    this.hideCancel= !this.hideCancel;
 }

When using tab key and when focused on cancel button, when user presses enter key, the cancel button disappears and the below Warning appears. Then Chrome/Firefox, when I press the tab key, focus goes to the "No" button below the Warning as expected. But in IE, focus goes to the top of the page.

I am not getting why it is happening. Is it because the currently focused element(cancel button) is removed from the DOM hence the focus is reset to the top on tabbing? Please help on how to prevent this in Internet Explorer.

1 Answers

There is a workaround to this by retaining the tab focus on the next element.

<button *ngIf="!hideCancel" (click)="toggleWarning(true);yesBtn.focus()">Cancel </button>
<!-- see how yesBtn reference is used to set the focus-->
 <div *ngIf="hideCancel">
      <p>Are you sure you want to cancel?</p>
 <button #yesBtn> Yes </button>
 <button (click)="toggleWarning(false)"> No </button>
 </div> 

Checkout the working example.

Related