3

I am using lightning-record-edit-form to display to users custom Opportunity form with the help of lightning-input-field. However, I am unable to set focus on a particular field.

I have a in a modal window, and I want to focus on this field when the modal opens so that the user doesn't have to use their mouse or tab to set focus.

However, when I try to set focus on Amount field using the below code, it didn't work.

  let fieldToFocus = this.template.querySelector("lightning-input-field[data-fieldname='Amount']");
    if(fieldToFocus){
        fieldToFocus.focus();
    }

Has anybody been able to make focus work with lightning-input-field?

1

2 Answers 2

2

Unfortunately lightning-input-field doesn't have @api method focus. You can use lightning-input instead.

0

Recent Updates:

Salesforce seems to have recently updated the global methods for lightning-input-field and snuck in a focus method, alongside the reset method that's been there: Input Field Specification

Updated Methods for lightning-input-field includes focus.

Sample code

component.html

<lightning-record-edit-form
        object-api-name={objectApiName}
        record-id={recordId}>
    <lightning-input-field field-name="Amount" data-fieldname="Amount"></lightning-input-field>
</lightning-record-edit-form>

component.js

Be sure to fire the focus() method when all rendering is completed, or asynchronously (setTimeout method with no delay) to ensure there are no errors on the method call.

let elem = this.template.querySelector("lightning-input-field[data-fieldname='Amount']");
setTimeout(() => elem.focus());

Note:

The focus() method does not work currently in the LWC Local Web Development Server. You'll need to deploy your code to an org to verify.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.