What Is Events in Lightning Web Components
What Is Events in Lightning Web Components
Events are used in LWC for components communication. There are typically
3 approaches for communication between the components using events.
1. Public Method
2. Public properties.
We have use the @api decorator to make the children properties /
method public available so parent.
Public Method
We can use the @api decorator to make the method public available
so parent can be able to call it directly using JavaScript API. For example
create one public method (which we need to access in parent component) in
ChildComponent with @api decorator like below
ChildComponent
@api
changeMessage(strString) {
this.Message = strString.toUpperCase();
}
To access the above child method in parent component we can do like that.
ParentComponent
this.template.querySelector('c-child-component').changeMessage(event.target.value);
The querySelector() method is a standard DOM API that returns the first element
that matches the selector
Lets take one example to pass value from parent component to child
component.
childComp.html
<template>
Message Will Come here from Parent Component :- {Message}
</template>
Step 2) Create javaScript method in child component to assign value on
child attribute
childComp.js
import { LightningElement, track, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@track Message;
@api
changeMessage(strString) {
this.Message = strString.toUpperCase();
}
}
Step 3) Create one Parent Component to call child component
ParentComponent.html
<template>
<lightning-card title="Parent to Child Demo">
<lightning-layout>
</lightning-layout>
</lightning-card>
</template>
Step 4) Now Create JavsScript method in Parent component to call child
method with “this.template.querySelector”.
ParentComponent.js
import { LightningElement } from 'lwc';
Public properties
You can make a component property public by prefacing it with the @api
decorator. Then, set the public property by an external component
Step 1) Create one child component component from where we will raise a
event
childComp.html
<template>
<lightning-card title="Child Component">
<div class="slds-m-around_medium">
<lightning-input name="textVal" label="Enter Text"
onchange={handleChange}></lightning-input>
</div>
</lightning-card>
</template>
Step 2) Now update Child Comp javaScript file to raise a CustomEvent with
text value
childComp.js
import { LightningElement } from 'lwc';
handleChange(event) {
event.preventDefault();
const name = event.target.value;
const selectEvent = new CustomEvent('mycustomevent', {
detail: name
});
this.dispatchEvent(selectEvent);
}
}
Step 3) Create one Parent component where we will handle the event
Now create parent component. We need to add prefix as “on” before the
custom event name and in parent component we need to invoke the event
listener as handleCustomEvent using onmycustomevent attribute. we
recommend that you conform with the DOM event standard.
No uppercase letters
No spaces
Use underscores to separate words
ParentComponent.html
<template>
<div class="slds-m-around_medium">
Value From Child : {msg}
<c-child-comp onmycustomevent={handleCustomEvent}></c-child-comp>
</div>
</template>
Now update parent component javaScript file and add handleCustomEvent
method
ParentComponent.js
import { LightningElement , track } from 'lwc';
Step 1) We can use the same above sample and do below change in parent
component
ParentComponent.js
import { LightningElement , track } from 'lwc';
constructor() {
super();
this.template.addEventListener('mycustomevent', this.handleCustomEvent.bind(this));
}
handleCustomEvent(event) {
const textVal = event.detail;
this.msg = textVal;
}
}
Remove onmycustomevent attribute from child component tag. like below
ParentComponent.html
<template>
<div class="slds-m-around_medium">
Value From Child : {msg}
<c-child-comp ></c-child-comp>
</div>
</template>
Step 3) Set the bubbles: true while raising the event like below
childComp.js
import { LightningElement } from 'lwc';
handleChange(event) {
event.preventDefault();
const name = event.target.value;
const selectEvent = new CustomEvent('mycustomevent', {
detail: name ,bubbles: true
});
this.dispatchEvent(selectEvent);
}
}
Event Propagation: When an event is fired the event is propagated up to
the DOM. Event propagation typically involves two phases event bubbling
and event capturing. The most commonly used event propagation phase for
handling events is event bubbling. In this case the event is triggered at the
child level and propagates up to the DOM. Where as event capturing phases
moves from top to bottom of the DOM. This phase is rarely used for event
handling.
The below picture shows the event phases both in capture and bubbles
phase. In LWC we have two flags which determines the behavior of event in
event bubbling phase.
reference:
1. Register
2. UnRegister
3. Fire
Follow below step for Pub Sub module
@track Message;
connectedCallback() {
registerListener('messageFromSpace', this.handleMessage, this);
}
handleMessage(myMessage) {
this.Message = myMessage;
//Add your code here
}
disconnectCallback() {
unregisterAllListeners(this);
}
}
Step 3) Fire the event
Fire the event from other Component. In that js file, We need to trigger the
event with name and value. Remember, we also need to send the page
reference attribute as current page reference for successful communication
OtherComponent.js
import { fireEvent } from 'c/pubsub';
import { CurrentPageReference } from 'lightning/navigation';
export default class OtherComponent extends LightningElement {
@track myMessage;
@wire(CurrentPageReference) pageRef;
sendMessage() {
fireEvent(this.pageRef, 'messageFromSpace', this.myMessage);
}
}
Demo