Reattach event listener after removing it, in Angular

Discussão em 'Angular' iniciado por Logic Tenacity, Dezembro 18, 2024.

  1. 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?

    Continue reading...

Compartilhe esta Página