I have the following problem: I am trying to throw an event from a child component to its parent with this code:
HeaderNotifications.html
<div style="width:100%" data-name={obj.notification.Name} key={obj.notification.Name} class="notification" onclick={handleChnage}>
<c-header-notification-item notification={obj.notification} icon={obj.icon} url={obj.url} onclose={handleRemoveChild}></c-header-notification-item>
</div>
HeaderNotifications.js
@api progressValue;
handleChnage(event) {
this.progressValue = Math.floor(Math.random() * 100);
const selectedEvent = new CustomEvent("onchange", {
detail: this.progressValue
});
// Dispatches the event.
this.dispatchEvent(selectedEvent);
}
Parent.html
<div class="button-container" style="position:relative">
<c-header-notifications notification-list={notificationList} ononchange={handleChild} user={user}></c-header-notifications>
</div>
Parent.js
@track progressValue = 0;
handleChild(event) {
this.progressValue = event.detail;
}
I have followed an example from the official documentation to build this code, but after trying this and other examples, with different options inside the customEvent like setting true bubbles and composed, but still when firing the onclick event it never communicates with the parent event, even trying different names.
I have these components inside a community, in which the parent is a horizontal bar that acts as a menu, and headerNotification is a child component that appears and disappears depending on the mouse over an icon that has the parent.
Thank you very much in advance!
Thank you very much for your answer Caspar. I have tried the code you suggested, but everything is still the same :S. It still doesn't pass to the parent method, even though I changed the name of the event, as you recommended:
Childlwc.js
_progressValue = 0;
@api set progressValue(value) { this._progressValue = value; } get progressValue() { return this._progressValue; }
handleChnage(event) { this.progressValue = Math.floor(Math.random() * 100); const selectedEvent = new CustomEvent("changevalue", { detail: this.progressValue }); // Dispatches the event. this.dispatchEvent(selectedEvent); }
ParentLWC.html
When clicked, the whole flow still works but does not reach the parent method. Could it be that the parent component is missing something to give visibility to the events?
new CustomEvent("onchange",
withnew CustomEvent("change",
as the "on" prefix is only required in the HTML attribute. Though I see you have used "ononchange" there.console.log
in listener & event fire in the child?getter/setter
code, you should do as @Bartheleway says - he's right, thedetail
attribute of the event expects an object. You have the classic 2+ bugs situation which makes fixes very difficult!getter/setter
is not needed in this situation