skip to Main Content

I have a modal with two buttons: one in the header and one in the modal body. Currently, when the modal opens, the focus automatically goes to the button in the modal body, but I want it to focus on the header button.

To address this, I wrote a function that adds an event listener to the modal button, and within that function, I included the code to focus on the header button.

My code is as follow:


triggerBtn(){
    const modalBtnDiv = document.querySelector('.modal-div');
    const headerBtn = document.querySelector('.header-btn');
    const myFocusEvent =(e) =>{
      headerBtn.focus(); 
      modalBtnDiv.removeEventListener('focus', myFocusEvent);
    };
    modalBtnDiv.addEventListener('focus', myFocusEvent);
}

However, the issue is that focusEvent() is triggered only once. When triggerBtn() is called again, focusEvent() doesn’t work because, after the listener is removed, it isn’t being reattached. And if I don’t remove the event listener, the focus stays on header btn and does not go to the next button.

Is there a way to resolve this and ensure the focus works as intended?

2

Answers


  1. As far as I understand your question, you want to autofocus on the button in the header. This can be achieved by adding autofocus to the button in your HTML template like so:

    <button class="my-button" (click)="doSomething($event)"
    

    And then you can get rid of the function triggerBtn()

    If you do need it to be set via the triggerBtn() function, you can achieve the same results by adjusting your function a little bit:

    
    // assuming Angular 17+
    
    @Component({
      template: '<button #headerBtn></button> <button #modalDiv></button>' // for simplicity
    })
    export class TestComponent {
      $headerBtn = viewChild<ElementRef>('headerBtn'); // Signal<ElementRef|undefined>
      $modalBtn = viewChild<ElementRef>('modalDiv'); // Signal<ElementRef|undefined>
    
      triggerBtn() {
        const headerBtn = this.$headerBtn();
        const modalBtn = this.$modalBtn();
        if(modalBtn) {
          modalBtn.nativeElement.blur(); // remove focus from modal button
        }
        if(headerBtn) {
          headerBtn.nativeElement.focus(); // focus the header button
        }
        
      }
    }
    
    

    Hope this helps!

    Login or Signup to reply.
  2. If you are accessing the btns from a library( I assume you have access to the library code ), you can write a common directive for the btns in the library (example : focus-btn) and use it to focus. You can access the element using elementref from angular core.

    I hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search