[SalesForce] LWC: How do we attach an onfocus event to an input-field

I'm trying to replicate a very simple functionality of copying a value in a lightning-input-field from another field onfocus.

Visualize something of a grid, where I would like to be able to Copy value of a field from top row onto the field that has the focus.

LWC Component:

<template>
    <div class="app slds-p-around_x-large">
        <lightning-record-edit-form object-api-name="Contact" class="quickForm1 slds-p-bottom_small">
            <lightning-messages></lightning-messages>
            <lightning-input-field field-name="FirstName"></lightning-input-field>
            <lightning-input-field field-name="LastName"></lightning-input-field>
            <lightning-input-field field-name="AccountId"></lightning-input-field>
        </lightning-record-edit-form>
        <lightning-record-edit-form object-api-name="Contact" class="quickForm2 slds-p-bottom_small">
            <lightning-messages></lightning-messages>
            <lightning-input-field name="fname" field-name="FirstName" onfocus={handleInputFocus}></lightning-input-field>
            <lightning-input-field name="lname" field-name="LastName" onfocus={handleInputFocus}></lightning-input-field>
            <lightning-input-field name="acc" field-name="AccountId" onfocus={handleInputFocus}></lightning-input-field>
        </lightning-record-edit-form>
    </div>
</template>

JS Code:

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {

    handleInputFocus(event) {
        console.log('onfocus fired', event.target.name);
    }

}

I could not find any onfocus event on lightning-input-field, is there a way I can make this work?

In above code snippet, the onfocus event does not fire at all, while I get no error in deploying the code.

Best Answer

You can add the tab-index property to 0 to make the element handle onfocus like this

<lightning-input-field  tabindex="0" onfocus={handleInputFocus} name="fname" field-name="FirstName" ></lightning-input-field>

JS

handleInputFocus(event) {
        console.log('onfocus fired');
        console.log(event.target.name);
    }
Related Topic