In Salesforce Lightning Web Components (LWC), Events establish connections between the components, such as sending messages from one component to another, triggering actions, and updating information.
With this, the events enable actions like button clicks, form submissions, or data updates. In this Salesforce tutorial, we will learn about events and how to handle events in Salesforce Lightning web components.
What are Events in Salesforce Lightning Web Components?
In Salesforce Lightning Web Components, events enable Lightning components to communicate with each other, allowing a component to send notifications to other components within the hierarchy.
To handle events in Lightning Web Components, we use the CustomEvent object to define and execute custom events within the LWC component and then refer to those events in the HTML template using the on attribute, allowing for declarative event handling between parent and child components or within the same component hierarchy.
There are typically three approaches for communication between the components using events.
- Parent-to-child event communication in Lightning web component.
- Custom Event Communication in Lightning Web Component (Child to Parent ).
- Publish Subscriber model in Lightning Web Component.
Parent-to-Child Event Communication in Lightning Web Component
For Parent-to-child event communication in the Lightning web component in Salesforce, we can pass the details from parent to child using two ways below:
- Public Method
- Public Properties
Parent-to-Child Event in LWC Through Public Method
In the Public method, we use the @api decorator to make the method publicly available so the parent component can call it directly using the JavaScript API.
Now, open the Salesforce developer console or VS Code Studio and follow the steps below.
1. First, we will create a child component with a template that will display the message from the parent component. For that, follow the code below in the HTML file.
<template>
Message from Parent: {message}
</template>
2. After this, enter the code below in the JavaScript file to assign the value in the child component.
import { LightningElement, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api message;
}
3. Now, create the Parent component to call the Child component. In this, we will pass data using a property in the parent component.
Enter the code below in the HTML file of the parent component.
<template>
<c-child-component message={parentMes