6

I am looking for the difference between event.target.value and event.detail.value.

It was mention that To communicate data to elements in the same shadow tree, use event.target and To communicate data to elements that aren’t in the same shadow tree, use event.detail.

Can anyone explain it with some example?

6

You are talking about event reparenting. Check this question - event.getSource() alternative in LWC? (considering origin reparenting).

Consider below components chain in LWC:

<c:parent>
    <c:child>
        <c:grandChild>

When event is fired by grandChild, you can access all the data- attributes and any other attributes directly in child component using event.target or event.currectTarget, However in parent component, event.target will refer to child component because of event reparenting and so you if you want to send some data to parent component from grandChild, you should use CustomEvent.detail for communicating the data within.

Note:
1. event.target or event.currentTarget will give you the reference of the element which fired the event and event.detail will give you the information of data in custom event
2. event.target or event.currentTarget is valid for both standard or custom event. event.detail is valid only for custom event. (in standard event, event.detail will return 1 always)

added

  1. You may get values in event.detail for lightning base custom components as they seem to fire event with data in detail as shown in this example
  • I used event.detail.value with a standard event to get the text entered in the input element. Take a look at this playground – dibocor Nov 18 at 9:14
  • @dibocor, thanks for sharing that, its actually because its lighting base component. You can check this link where you will not get for native elements – salesforce-sas Nov 18 at 9:25
3

CustomEvent's provide the detail field for it to avoid any conflict with other event properties.

while

The target property of the Event interface is a reference to the object that dispatched the event.

as per https://developer.mozilla.org/en-US/docs/Web/API/Event/target

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