[SalesForce] Lightning Web Components focus not working

I am working on a requirement wherein I display a list of error messages on the parent component and there are certain lightning input fields in the child component.

On click of the error message, I need to highlight the corresponding field in child component in red, showing error is related to that field.

SO, for example. I have an error message that says Name should not be empty, in that case, I need to highlight the input field for Name in the child component.

To achieve this, I'm passing the id value to a method in the child component, which relates to both the id and data-id attributes of the input field to be highlighted/focused on.

I used a console message in child component method to verify if I'm getting the correct data-id, and it sends the correct data-id but the focus doesn't seem to be working .

Below is the code snippet of how I'm trying to focus.

@api
    focusOnError(sfieldId){
        /* eslint-disable no-console */
        console.log('Id Recieved in child component : ',sfieldId);
        this.template.querySelector(`[data-id="${this.sfieldId}"]`).focus();
    }

And this is the css that I used :

lightning-input:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}

Can someone please tell the right way to use focus to take to the specific field and highlight.

Thanks.

Best Answer

I agree with Eric as its difficult to say without looking at the rest of the markup.

But, what I can still notice from the markup given above is that you're trying to refer the global property sfieldId by using this.sfieldId in the querySelector, while you might have to use the argument value passed to the method, which is the local method property.

So try changing it to :

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