Catch the event of clicking the “Clear” button in lightning-input type=”search”

htmljavascriptlightning-web-components

How to catch the event of clicking the "Clear" button in lightning-input type="search"? In the salesforce documentation, this is not specified, I found a similar question, but for visualforce ^ https://developer.salesforce.com/forums/?id=9060G0000005aZ8QAI, and I could not compose anything useful for myself by analogy. This question concerns LWC and salesforce.

This button:
enter image description here

Best Answer

It's stated at very bottom of the documentation page (emphasis mine)

commit
The event fired when you press Enter after interacting with the input, or move away from the input so it loses focus. For the input type search the event is also fired when you click the "x" button to clear the search.

HTML:

<lightning-input
    name="enter-search"
    label="Search when user hits the 'enter' key"
    type="search"
    oncommit={handleClear}
></lightning-input>

JS:

handleClear(event) {
    if (!event.target.value.length) {
        console.log('clear');
    }
}

Since it's called when the input loses focus too, if you want to handle only the "clear" action you need the if on target.value.length.