I am trying to implement custom event handling function using salesforce lwc event handling. While dispatching event from child to parent , custom event handling function handleCustomEvent
is not getting triggered by using this.template.addEventListener defined in constructor.
Child component html file like the following,
<template>
<lightning-card title="Child Component">
<div>
<lightning-input name="textVal" label="Enter Text" onchange={handleChange}>
</lightning-input>
</div>
</lightning-card>
</template>
child .js file ,
export default class ChildCus extends LightningElement {
handleChange(event) {
event.preventDefault();
const name = event.target.value;
const selectEvent = new CustomEvent('mycustomevent', {
detail: name,bubbles: true
});
this.dispatchEvent(selectEvent);
}
}
Parent component html file,
<template>
<div>
Value From Child : {msg}
<c-child-comp ></c-child-comp>
</div>
</template>
Parent component .js file,
export default class ParentCus extends LightningElement {
@track msg;
constructor() {
super();
this.template.querySelector('c-child-comp').addEventListener(
'mycustomevent',
this.myCustomEventHandler
);
}
myCustomEventHandler = (event) => {
this.handleCustomEvent(event);
}
handleCustomEvent(event) {
console.log("Test Point2");
const textVal = event.detail;
this.msg = textVal;
}
}
UPDATE
according to answered suggestion , I am getting Uncaught SyntaxError: Unexpected token ':' (at childComp:1:10)
in parent console and getting following screenshot while loading page,
In parent component js file, constructor is working without any error. But handleCustomEvent
function is not getting triggered. Can anyone guide me to resolve this issue why its happening?
onmycustomevent
to bind a handler to that event on the child markup within the parent template?this.addEventListener
andthis.template.addEventListener
.