[SalesForce] Set focus in LWC on anchor tag

I need to set focus on the element inside an LWC component on button click. I have tried with adding data-id but I'm still unable to set focus on it.

<template if:true={showDiv}>
    <div title="My informative div" role="alert"  aria-live="assertive" >
        <a data-id="myFocussedLink" onclick={doSomething} href={customMessage} tabindex="0">{customMessage}</a>
    </div>
</template>

TabIndex is not setting the focus on the link.

In JavaScript, below line is returning me null so I can set focus and receive an error:

this.template.querySelector(`[data-id="${myFocussedLink}"]`)).focus();

Div is visible when some other action on the page is complete. I can see the div but the focus is not set on the link as soon as div renders on the page. Could someone please help.

Best Answer

When you set showDiv, the system needs time to redraw the elements, which don't happen in real time. You need a short breather for the DOM to catch up:

  focusAnchor() {
    this.showDiv = true;
    setTimeout(()=>this.template.querySelector('[data-id="myFocussedLink"]').focus());
  }

P.S. [data-id="${myFocussedLink}"] is trying to insert the variable myFocussedLink into the string instead of the actual ID. I'm not sure if you meant to do this, or just got "lost" trying different things.

Related Topic