Update: This answer describes how to use the keyboard events to solve the problem. However, as pointed out by @ministe2003 in the comment, onchange
event seems to work too and the below mentioned solution can be used with onchange
event instead of onkeyup
event.
Standard DOM keyboard events such as onkeyup
, onkeydown
& onkeypress
seem to work in lightning-datatable
, although this has not be explicitly documented in the LWC developer guide (or the Component Reference).
I don't know if there was a specific reason why Salesforce chose to leave out these events in their documentation or if they may (or may not) be supported in future or if they might not work consistently as expected. I've only tried them in the Lightning playground and they worked fine. So, I'm going to assume that it should work fine in an actual SF org too. I would encourage you to adopt this at your discretion and to perform a thorough testing to ensure it works properly.
In the HTML file of the child component, define the key event, as shown in the sample snippet below:
<lightning-datatable
key-field="id"
data={data}
columns={columns}
onkeyup={handleKeyUp}>
</lightning-datatable>
And, the corresponding JS method code snippet should something like this:
handleKeyUp(event){
// Write additional code to identify the key pressed from the key code, if required
constant tableEditedEvent = new CustomEvent('tableedit');
this.dispatchEvent(tableEditedEvent);
}
In the parent component, handle the ontableedit
event and disable the appropriate button element.
This may not be the best possible solution (with good user experience), but in lack of better in-built alternatives with lightning-datatable
, this should get your work done. You will have to get a bit creative in writing code to identify the key pressed (by key code) and avoid disabling the parent component button, when not needed. Additionally, if the user edited a cell and reverted the changes immediately before moving the focus from the current cell, the parent component button would already be disabled by the custom event dispatched by keyUp event handler. So, you will have to write code in the oncellchange
event handler to check if no changes are found in the draftValues
property (and/or additional custom properties) and re-enable the parent component button. This piece of code will execute only after the user clicks on the disabled button or elsewhere on the web page, but will re-enable the button immediately. This would become a minor or major inconvenience to user, depending on how business looks at this. You could provide alternatives like a checkbox (with label as No change in data - Enable the button
) and educate user to click the checkbox, when needed.
Best Answer
id
shouldn't be used, because it is used by the framework for rendering purposes. Instead, just use a data attribute to specify the name:...
...
Edit: I also created a quick playground that demonstrates this.